Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings
This repository was archived by the owner on Jan 31, 2024. It is now read-only.

Testing utilities that allow you to reuse your Storybook stories in your React unit tests!

License

NotificationsYou must be signed in to change notification settings

storybookjs/testing-react

Repository files navigation

Storybook React Testing

Testing utilities that allow you to reuse your stories in your unit tests


⚠️ Attention!

If you're using Storybook 7, you need to read this section. Otherwise, feel free to skip it.

@storybook/testing-react has been promoted to a first-class Storybook functionality. This means thatyou no longer need this package. Instead, you can import the same utilities, but from the@storybook/react package. Additionally, the internals ofcomposeStories andcomposeStory have been revamped, so the way a story is composed is more accurate. The@storybook/testing-react package will be deprecated, so we recommend you to migrate.

Please do the following:

  1. Uninstall this package
  2. Update your imports
- import { composeStories } from '@storybook/testing-react';+ import { composeStories } from '@storybook/react';// OR- import { setProjectAnnotations } from '@storybook/testing-react';+ import { setProjectAnnotations } from '@storybook/react';

The problem

You are usingStorybook for your components and writing tests for them withjest, most likely alongsideEnzyme orReact testing library. In your Storybook stories, you already defined the scenarios of your components. You also set up the necessary decorators (theming, routing, state management, etc.) to make them all render correctly. When you're writing tests, you also end up defining scenarios of your components, as well as setting up the necessary decorators. By doing the same thing twice, you feel like you're spending too much effort, making writing and maintaining stories/tests become less like fun and more like a burden.

The solution

@storybook/testing-react is a solution to reuse your Storybook stories in your React tests. By reusing your stories in your tests, you have a catalog of component scenarios ready to be tested. Allargs anddecorators from yourstory and itsmeta, and alsoglobal decorators, will be composed by this library and returned to you in a simple component. This way, in your unit tests, all you have to do is select which story you want to render, and all the necessary setup will be already done for you. This is the missing piece that allows for better shareability and maintenance between writing tests and writing Storybook stories.

Installation

This library should be installed as one of your project'sdevDependencies:

vianpm

npm install --save-dev @storybook/testing-react

or viayarn

yarn add --dev @storybook/testing-react

Setup

Storybook 6 and Component Story Format

This library requires you to be using Storybook version 6,Component Story Format (CSF) andhoisted CSF annotations, which is the recommended way to write stories since Storybook 6.

Essentially, if you use Storybook 6 and your stories look similar to this, you're good to go!

// CSF: default export (meta) + named exports (stories)exportdefault{title:'Example/Button',component:Button,};constPrimary=args=><Button{...args}/>;// or with Template.bind({})Primary.args={primary:true,};

Global config

This is an optional step. If you don't haveglobal decorators, there's no need to do this. However, if you do, this is a necessary step for your global decorators to be applied.

If you have global decorators/parameters/etc and want them applied to your stories when testing them, you first need to set this up. You can do this by adding to or creating a jestsetup file:

// setupFile.js <-- this will run before the tests in jest.import{setProjectAnnotations}from'@storybook/testing-react';import*asglobalStorybookConfigfrom'./.storybook/preview';// path of your preview.js filesetProjectAnnotations(globalStorybookConfig);

For the setup file to be picked up, you need to pass it as an option to jest in your test command:

// package.json{"test":"react-scripts test --setupFiles ./setupFile.js"}

Usage

composeStories

composeStories will process all stories from the component you specify, compose args/decorators in all of them and return an object containing the composed stories.

If you use the composed story (e.g. PrimaryButton), the component will render with the args that are passed in the story. However, you are free to pass any props on top of the component, and those props will override the default values passed in the story's args.

import{render,screen}from'@testing-library/react';import{composeStories}from'@storybook/testing-react';import*asstoriesfrom'./Button.stories';// import all stories from the stories file// Every component that is returned maps 1:1 with the stories, but they already contain all decorators from story level, meta level and global level.const{ Primary, Secondary}=composeStories(stories);test('renders primary button with default args',()=>{render(<Primary/>);constbuttonElement=screen.getByText(/Textcomingfromargsinstoriesfile!/i);expect(buttonElement).not.toBeNull();});test('renders primary button with overriden props',()=>{render(<Primary>Hello world</Primary>);// you can override props and they will get merged with values from the Story's argsconstbuttonElement=screen.getByText(/Helloworld/i);expect(buttonElement).not.toBeNull();});

composeStory

You can usecomposeStory if you wish to apply it for a single story rather than all of your stories. You need to pass the meta (default export) as well.

import{render,screen}from'@testing-library/react';import{composeStory}from'@storybook/testing-react';importMeta,{PrimaryasPrimaryStory}from'./Button.stories';// Returns a component that already contain all decorators from story level, meta level and global level.constPrimary=composeStory(PrimaryStory,Meta);test('onclick handler is called',()=>{constonClickSpy=jest.fn();render(<PrimaryonClick={onClickSpy}/>);constbuttonElement=screen.getByRole('button');buttonElement.click();expect(onClickSpy).toHaveBeenCalled();});

setting project annotations tocomposeStory orcomposeStories

setProjectAnnotations is intended to apply all the global configurations that are defined in your.storybook/preview.js file. This means that you might get unintended side-effects in case your preview.js imports certain mocks or other things you actually do not want to execute in your test files. If this is your case and you still need to provide some annotation overrides (decorators, parameters, etc) that normally come from preview.js, you can pass them directly as the optional last argument of bothcomposeStories andcomposeStory functions:

composeStories:

import*asstoriesfrom'./Button.stories'// default behavior: uses overrides from setProjectAnnotationsconst{ Primary}=composeStories(stories)// custom behavior: uses overrides defined locallyconst{ Primary}=composeStories(stories,{decorators:[...],globalTypes:{...},parameters:{...})

composeStory:

import*asstoriesfrom'./Button.stories'// default behavior: uses overrides from setProjectAnnotationsconstPrimary=composeStory(stories.Primary,stories.default)// custom behavior: uses overrides defined locallyconstPrimary=composeStory(stories.Primary,stories.default,{decorators:[...],globalTypes:{...},parameters:{...})

Reusing story properties

The components returned bycomposeStories orcomposeStory not only can be rendered as React components, but also come with the combined properties from story, meta and global configuration. This means that if you want to accessargs orparameters, for instance, you can do so:

import{render,screen}from'@testing-library/react';import{composeStory}from'@storybook/testing-react';import*asstoriesfrom'./Button.stories';const{ Primary}=composeStories(stories);test('reuses args from composed story',()=>{render(<Primary/>);constbuttonElement=screen.getByRole('button');// Testing against values coming from the story itself! No need for duplicationexpect(buttonElement.textContent).toEqual(Primary.args.children);});

CSF3

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

1 - Yourstory has arender method2 - Or yourmeta has arender method3 - Or yourmeta contains acomponent property

// Example 1: Meta with component propertyexportdefault{title:'Button',component:Button,// <-- This is strictly necessary};// Example 2: Meta with render method:exportdefault{title:'Button',render:args=><Button{...args}/>,};// Example 3: Story with render method:exportconstPrimary={render:args=><Button{...args}/>,};

Interactions with play function

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

In@storybook/testing-react, theplay 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:

exportconstInputFieldFilled:Story<InputFieldProps>={play:async({ canvasElement})=>{constcanvas=within(canvasElement);awaituserEvent.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 inputawaitInputFieldFilled.play({canvasElement:container});constinput=screen.getByRole('textbox')asHTMLInputElement;expect(input.value).toEqual('Hello world!');});

Batch testing all stories from a file

Rather than specifying test by test manually, you can also run automated tests by usingtest.each in combination withcomposeStories. Here's an example for doing snapshot tests in all stories from a file:

import*asstoriesfrom'./Button.stories';consttestCases=Object.values(composeStories(stories)).map((Story)=>[// The ! is necessary in Typescript only, as the property is part of a partial typeStory.storyName!,Story,]);// Batch snapshot testingtest.each(testCases)('Renders %s story',async(_storyName,Story)=>{consttree=awaitrender(<Story/>);expect(tree.baseElement).toMatchSnapshot();});

Typescript

@storybook/testing-react is typescript ready and provides autocompletion to easily detect all stories of your component:

component autocompletion

It also provides the props of the components just as you would normally expect when using them directly in your tests:

props autocompletion

Type inference is only possible in projects that have eitherstrict orstrictBindApplyCall modes set totrue in theirtsconfig.json file. You also need a TypeScript version over 4.0.0. If you don't have proper type inference, this might be the reason.

// tsconfig.json{"compilerOptions": {// ..."strict":true,// You need either this option"strictBindCallApply":true// or this option// ...  }// ...}

Disclaimer

For the types to be automatically picked up, your stories must be typed. See an example:

importReactfrom'react';import{Story,Meta}from'@storybook/react';import{Button,ButtonProps}from'./Button';exportdefault{title:'Components/Button',component:Button,}asMeta;// Story<Props> is the key piece needed for typescript validationconstTemplate:Story<ButtonProps>=args=><Button{...args}/>;exportconstPrimary=Template.bind({});Primary.args={children:'foo',size:'large',};

License

MIT

About

Testing utilities that allow you to reuse your Storybook stories in your React unit tests!

Topics

Resources

License

Contributing

Stars

Watchers

Forks

Packages

No packages published

Contributors19


[8]ページ先頭

©2009-2025 Movatter.jp