fbredius/storybook

View on GitHub
docs/snippets/react/my-component-play-function-with-canvas.ts.mdx

Summary

Maintainability
Test Coverage
```ts
// MyComponent.stories.ts|tsx

import React from 'react';

import { ComponentStory, ComponentMeta } from '@storybook/react';

import { userEvent, within } from '@storybook/testing-library';

import { MyComponent } from './MyComponent';

export default {
  /* 👇 The title prop is optional.
  * See https://storybook.js.org/docs/react/configure/overview#configure-story-loading
  * to learn how to generate automatic titles
  */
  title: 'WithCanvasElement',
  component: MyComponent,
} as ComponentMeta<typeof MyComponent>;

const Template: ComponentStory<typeof MyComponent> = (args) => <MyComponent {...args} />;

export const ExampleStory = Template.bind({});
ExampleStory.play = async ({ canvasElement }) => {
  // Assigns canvas to the component root element
  const canvas = within(canvasElement);

  // Starts querying from the component's root element
  await userEvent.type(canvas.getByTestId('example-element'), 'something');
  await userEvent.click(canvas.getByRole('another-element'));
};
```