Skip to content

.play() function not defined when using msw loader #166

@MehediH

Description

@MehediH

Hi! thanks for your work on this library! I have been having some issues with inconsistent mocking when running Jest tests (with portable stories) locally vs in CI. Currently, I use .load() to load the msw loaders in test.

Here's my storybook preview:

import type { Preview } from '@storybook/react';
import { initialize, mswLoader } from 'msw-storybook-addon';

import { initialHandlers } from '../src/utils/msw/initialHandlers';

initialize(
  {
    onUnhandledRequest: 'bypass',
  },
  // initial handlers required by the app
  [...initialHandlers]
);

const preview: Preview = {
  parameters: {
    controls: {
      expanded: true,
    },
  },
  loaders: [
    mswLoader
  ],
};

export default preview;

And here's my setupTests:

require('@testing-library/jest-dom');
require('jest-location-mock');

import { setProjectAnnotations } from '@storybook/react';

import * as previewAnnotations from '../.storybook/preview';

const annotations = setProjectAnnotations([previewAnnotations]);

beforeAll(annotations.beforeAll);

import { getWorker } from 'msw-storybook-addon';

const worker = getWorker();

afterEach(() => {
  worker.resetHandlers();
});

When running tests:

import { composeStories } from '@storybook/react';
import { render, screen } from '@testing-library/react';
import React from 'react';

import * as ExampleComponent from './ExampleComponent.stories';

const { Default } = composeStories(ExampleComponent);

describe('Test', () => {
  it('renders successfully with data', async () => {
    await Default.play?.();
 
    render(<Default/>);

    expect(await screen.findByTestId('example-test-id')).toBeInTheDocument();
  });
});

but the .play() above does not work - it is not defined. load() is defined, but play() is not. According to the library docs here → https://github.com/mswjs/msw-storybook-addon?tab=readme-ov-file#storybook-82-or-higher, we should use play() - but this function is not defined for some reason.

It is possible that I have not set up the project annotations correctly as the doc states, but it will be useful to know what "correctly" means here.

Additionally, when you have the time, it would be awesome to have a simple example of how the ideal Storybook addon + Jest test setup should look like. Thank you once again!

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions