storybookjs / testing-react

Testing utilities that allow you to reuse your Storybook stories in your React unit tests!
MIT License
588 stars 24 forks source link

Feature/run play function typed #57

Closed yannbf closed 2 years ago

yannbf commented 2 years ago

Issue: N/A

What Changed

Checklist

Check the ones applicable to your change:

Change Type

Indicate the type of change your pull request is:

Release Notes

Breaking changes

Updates Storybook peer dependency to 6.4

Features

CSF3

Storybook 6.4 released a new version of CSF, where the story can also be an object. This is supported in @storybook/testing-react, but you have to match the requisites:

1 - Either your story has a render method or your meta contains a component property:

// Example 1: Meta with component property
export default {
  title: 'Button',
  component: Button // <-- This is strictly necessary
}

// Example 2: Story with render method:
export const Primary = {
  render: (args) => <Button {...args}>
}

Play function

Storybook 6.4 also brings a new function called play, where you can write automated interactions to the story.

In @storybook/testing-react, the play function does not run automatically for you, but rather comes in the returned component, and you can execute it as you please.

Consider the following example:

export const InputFieldFilled: Story<InputFieldProps> = {
  play: async ({ canvasElement }) => {
    const canvas = within(canvasElement);
    await userEvent.type(canvas.getByRole('textbox'), 'Hello world!');
  },
};

You can use the play function like this:

const { InputFieldFilled } = composeStories(stories);

test('renders with play function', async () => {
  const { container } = render(<InputFieldFilled />);

  // pass container as canvasElement and play an interaction that fills the input
  await InputFieldFilled.play({ canvasElement: container });

  const input = screen.getByRole('textbox') as HTMLInputElement;
  expect(input.value).toEqual('Hello world!');
});
yannbf commented 2 years ago

Thank you so much for your help along the way @tmeasday @ndelangen, you are incredible!

yannbf commented 2 years ago

Alright, unfortunately for people using the best practice for addon-interactions (using @storybook/testing-library instead of @testing-library/*) this will break. It's not a problem in @storybook/testing-react, but it is a problem in @storybook/testing-library. Once that is fixed we can proceed with the tests in this PR.

Here's how the error looks like: image

And it has been documented before in https://github.com/storybookjs/storybook/issues/16382#issuecomment-945920087