• This repository has been archived on 31/Jan/2024
  • Stars
    star
    588
  • Rank 76,022 (Top 2 %)
  • Language
    TypeScript
  • License
    MIT License
  • Created over 3 years ago
  • Updated over 1 year ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

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

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 that you no longer need this package. Instead, you can import the same utilities, but from the @storybook/react package. Additionally, the internals of composeStories and composeStory 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 using Storybook for your components and writing tests for them with jest, most likely alongside Enzyme or React 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. All args and decorators from your story and its meta, and also global 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's devDependencies:

via npm

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

or via yarn

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) and hoisted 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)
export default {
  title: 'Example/Button',
  component: Button,
};

const Primary = args => <Button {...args} />; // or with Template.bind({})
Primary.args = {
  primary: true,
};

Global config

This is an optional step. If you don't have global 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 jest setup file:

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

setProjectAnnotations(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 * as stories from './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 />);
  const buttonElement = screen.getByText(
    /Text coming from args in stories file!/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 args
  const buttonElement = screen.getByText(/Hello world/i);
  expect(buttonElement).not.toBeNull();
});

composeStory

You can use composeStory 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';
import Meta, { Primary as PrimaryStory } from './Button.stories';

// Returns a component that already contain all decorators from story level, meta level and global level.
const Primary = composeStory(PrimaryStory, Meta);

test('onclick handler is called', () => {
  const onClickSpy = jest.fn();
  render(<Primary onClick={onClickSpy} />);
  const buttonElement = screen.getByRole('button');
  buttonElement.click();
  expect(onClickSpy).toHaveBeenCalled();
});

setting project annotations to composeStory or composeStories

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 both composeStories and composeStory functions:

composeStories:

import * as stories from './Button.stories'

// default behavior: uses overrides from setProjectAnnotations
const { Primary } = composeStories(stories)

// custom behavior: uses overrides defined locally
const { Primary } = composeStories(stories, { decorators: [...], globalTypes: {...}, parameters: {...})

composeStory:

import * as stories from './Button.stories'

// default behavior: uses overrides from setProjectAnnotations
const Primary = composeStory(stories.Primary, stories.default)

// custom behavior: uses overrides defined locally
const Primary = composeStory(stories.Primary, stories.default, { decorators: [...], globalTypes: {...}, parameters: {...})

Reusing story properties

The components returned by composeStories or composeStory 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 access args or parameters, for instance, you can do so:

import { render, screen } from '@testing-library/react';
import { composeStory } from '@storybook/testing-react';
import * as stories from './Button.stories';

const { Primary } = composeStories(stories);

test('reuses args from composed story', () => {
  render(<Primary />);

  const buttonElement = screen.getByRole('button');
  // Testing against values coming from the story itself! No need for duplication
  expect(buttonElement.textContent).toEqual(Primary.args.children);
});

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 one of the requisites:

1 - Your story has a render method 2 - Or your meta has a render method 3 - 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: Meta with render method:
export default {
  title: 'Button',
  render: args => <Button {...args} />,
};

// Example 3: Story with render method:
export const Primary = {
  render: args => <Button {...args} />,
};

Interactions with 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!');
});

Batch testing all stories from a file

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

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

const testCases = Object.values(composeStories(stories)).map((Story) => [
  // The ! is necessary in Typescript only, as the property is part of a partial type
  Story.storyName!,
  Story,
]);
// Batch snapshot testing
test.each(testCases)('Renders %s story', async (_storyName, Story) => {
  const tree = await render(<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 either strict or strictBindApplyCall modes set to true in their tsconfig.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:

import React from 'react';
import { Story, Meta } from '@storybook/react';

import { Button, ButtonProps } from './Button';

export default {
  title: 'Components/Button',
  component: Button,
} as Meta;

// Story<Props> is the key piece needed for typescript validation
const Template: Story<ButtonProps> = args => <Button {...args} />;

export const Primary = Template.bind({});
Primary.args = {
  children: 'foo',
  size: 'large',
};

License

MIT

More Repositories

1

storybook

Storybook is the industry standard workshop for building, documenting, and testing UI components in isolation
TypeScript
83,871
star
2

design-system

πŸ—ƒ Storybook Design System
TypeScript
1,910
star
3

react-native

πŸ““ Storybook for React Native!
TypeScript
1,024
star
4

builder-vite

A builder plugin to run and build Storybooks with Vite
TypeScript
890
star
5

addon-designs

A Storybook addon that embeds Figma, websites, or images in the addon panel.
TypeScript
875
star
6

react-inspector

πŸ” Power of Browser DevTools inspectors right inside your React app
TypeScript
768
star
7

presets

🧩 Presets for Storybook
TypeScript
424
star
8

marksy

πŸ“‘ A markdown to custom VDOM components library
JavaScript
354
star
9

vue-cli-plugin-storybook

Vue CLI plugin for Storybook
JavaScript
279
star
10

eslint-plugin-storybook

πŸŽ—Official ESLint plugin for Storybook
TypeScript
243
star
11

addon-jsx

This Storybook addon show you the JSX / template of the story
TypeScript
236
star
12

test-runner

πŸš• Turn stories into executable tests
TypeScript
226
star
13

frontpage

🌐 The website for storybook.js.org
TypeScript
214
star
14

storybook-addon-console

storybook-addon. Redirects console output into action logger panel
TypeScript
200
star
15

native

πŸ“± Storybook for Native: iOS, Android, Flutter
TypeScript
186
star
16

telejson

πŸ›° JSON parse & stringify with support for cyclic objects, functions, dates, regex, infinity, undefined, null, NaN, Classes, Instances
TypeScript
167
star
17

babel-plugin-react-docgen

πŸ“ Babel plugin to add react-docgen info into your code.
JavaScript
162
star
18

addon-kit

Everything you need to build a Storybook addon
TypeScript
137
star
19

vs-code-plugin

Aesop: a VSCode Extension to stage Storybook stories inside your IDE.
TypeScript
131
star
20

addon-svelte-csf

[Incubation] CSF using Svelte components.
TypeScript
99
star
21

brand

🎨 Materials for your articles and talks about storybook
93
star
22

addon-react-native-web

Build react-native-web projects in Storybook for React
TypeScript
76
star
23

desktop

πŸ’» Desktop app for all your Storybooks
JavaScript
72
star
24

testing-library

Instrumented version of Testing Library for Storybook Interactions
TypeScript
56
star
25

require-context.macro

πŸ–‡ A Babel macro needed for some advanced Storybook setups. Used to mock webpack's context function in test environments.
JavaScript
48
star
26

solidjs

SolidJS integration for Storybook, maintained by the community
TypeScript
44
star
27

addon-styling

A base addon for configuring popular styling tools
TypeScript
44
star
28

ember-cli-storybook

πŸ“’ Ember storybook adapter
JavaScript
37
star
29

sandboxes

MDX
35
star
30

aem

Adobe Experience Manager Storybook app with events, knobs, docs, addons, and more
JavaScript
33
star
31

paths.macro

πŸ‘£ Babel plugin that returns an object containing paths like __dirname and __filename as static values
JavaScript
32
star
32

shout-out-kit

An image generation API template
JavaScript
30
star
33

linter-config

πŸ“ ESlint config, Prettier config, Remark config for storybook
JavaScript
27
star
34

addon-styling-webpack

Successor to @storybook/addon-styling. Configure the styles of your webpack storybook with ease!
TypeScript
26
star
35

SBNext

A future SB
JavaScript
26
star
36

addon-postcss

This Storybook addon can be used to run the PostCSS preprocessor against your stories.
JavaScript
21
star
37

addon-measure

JavaScript
20
star
38

addon-coverage

TypeScript
19
star
39

jest

Instrumented version of Jest for Storybook Interactions
TypeScript
18
star
40

nextjs-example

Example app showing Storybook integrated with Next.js (v11) pages
JavaScript
18
star
41

testing-vue3

Testing utilities that allow you to reuse your stories in your unit tests
TypeScript
16
star
42

bench

Storybook benchmark
TypeScript
15
star
43

nextjs-server

Embedded Storybook in Next.js
TypeScript
14
star
44

mdx2-csf

MDX to CSF compiler using MDXv2
TypeScript
14
star
45

testing-angular

TypeScript
13
star
46

addon-knobs

Storybook addon prop editor component
TypeScript
12
star
47

storybook-rsc-demo

Project demo to showcase Storybook's new module mocking functionality
TypeScript
12
star
48

testing-vue

TypeScript
10
star
49

addon-google-analytics

Storybook addon for google analytics
JavaScript
10
star
50

jest-storybook

Test storybook stories automagically using Jest. πŸ§™πŸ»β€β™€οΈ
JavaScript
9
star
51

storybook-nuxt

Storybook integration for Nuxt Framework - Unleashing the power of Storybook in Nuxt/Vue Land!
TypeScript
9
star
52

icons

Library of icons used in apps and marketing sites
TypeScript
9
star
53

expect

Browser-compatible version of Jest's `expect`
JavaScript
8
star
54

create-svelte-with-args

A small CLI wrapper around the create-svelte package that enables you to replace the interactive prompts with CLI arguments.
JavaScript
8
star
55

addon-queryparams

parameter addon for storybook
TypeScript
8
star
56

addon-cssresources

A storybook addon to switch between css resources at runtime for your story
TypeScript
7
star
57

addon-graphql

Storybook addon to display the GraphiQL IDE
TypeScript
7
star
58

action

🚒 WIP, storybook github action - build your storybook from github
JavaScript
7
star
59

addon-events

Add events to your Storybook stories.
TypeScript
6
star
60

addon-design-assets

Design asset preview for storybook
JavaScript
6
star
61

vue3-code-examples

it is a repo to show Vuetify implementation with new @storybook/vue3 reactive mode
TypeScript
6
star
62

addon-react-native-server

A replacement for @storybook/react-native-server which will enable multiple devices to sync over websockets
TypeScript
6
star
63

raycast-extension-sandboxes

A Raycast Extension to quickly create sandboxes online or locally
TypeScript
6
star
64

marko

Storybook framework support for marko
TypeScript
6
star
65

addon-onboarding

TypeScript
6
star
66

storybook-day

Storybook day website
TypeScript
5
star
67

addon-ie11

JavaScript
5
star
68

components-marketing

TypeScript
5
star
69

web

Storybook documentation site
TypeScript
5
star
70

governance

βš–οΈ Storybook governance and community policies
4
star
71

docs2-prototype

TypeScript
4
star
72

community

πŸ™Œ Storybook community resources: monthly meetings, meetups, conferences
4
star
73

mdx1-csf

MDX to CSF compiler using MDXv1
TypeScript
4
star
74

docs-mdx

TypeScript
3
star
75

addon-angular-ivy

TypeScript
3
star
76

babel-plugin-named-exports-order

Babel plugin for preserving exports order across transforms
JavaScript
3
star
77

ember

Storybook for Ember
TypeScript
3
star
78

addon-bench

Storybook benchmarking helper
JavaScript
3
star
79

repro-react-cra

Reproduction template for Create React App
JavaScript
3
star
80

react-native-demo

Storybook for React Native monorepo
2
star
81

repro-templates

WIP
JavaScript
2
star
82

eslint-config-storybook

πŸ”— wrapper around our @storybook/linter-config package
JavaScript
2
star
83

vitest-plugin

Highly experimental Storybook vitest plugin
TypeScript
2
star
84

.github

Repo community health files
1
star
85

e2e-testing-starter

JavaScript
1
star
86

vue3-autogen-controls

TypeScript
1
star
87

stencil-builder-test

TypeScript
1
star
88

svelte-csf-demo

Demonstrating Svelte CSF (@storybook/addon-svelte-csf) vs regular CSF3
Svelte
1
star
89

auto-config

TypeScript
1
star
90

external-sandboxes

MDX
1
star
91

addon-webpack5-compiler-swc

Adds SWC as a Webpack5 compiler to Storybook
TypeScript
1
star
92

playwright-ct

Playwright component testing against a Storybook instance
TypeScript
1
star
93

create-webpack5-react

JavaScript
1
star
94

addon-webpack5-compiler-babel

Adds babel as a Webpack5 compiler to Storybook
TypeScript
1
star
95

vite-plugin-storybook-nextjs

TypeScript
1
star