Product
Socket Now Supports uv.lock Files
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
@storybook/testing-react
Advanced tools
Testing utilities that allow you to reuse your stories in your unit tests
@storybook/testing-react is a package that provides utilities for testing React components that are built with Storybook. It allows you to reuse your Storybook stories in your tests, ensuring consistency between your stories and your tests.
Render a Story
This feature allows you to render a Storybook story in a test environment. The `composeStories` function imports all stories from a file and allows you to use them in your tests. In this example, the `Primary` story from `Button.stories` is rendered and tested.
import { render } from '@testing-library/react';
import { composeStories } from '@storybook/testing-react';
import * as stories from './Button.stories';
const { Primary } = composeStories(stories);
test('renders primary button', () => {
const { getByText } = render(<Primary />);
expect(getByText('Primary Button')).toBeInTheDocument();
});
Test Story Interactions
This feature allows you to test interactions within your stories. In this example, the `Clickable` story from `Button.stories` is rendered, and a click event is simulated on the button. The test then checks if the button's text content changes as expected.
import { render, fireEvent } from '@testing-library/react';
import { composeStories } from '@storybook/testing-react';
import * as stories from './Button.stories';
const { Clickable } = composeStories(stories);
test('button click', () => {
const { getByText } = render(<Clickable />);
const button = getByText('Click Me');
fireEvent.click(button);
expect(button).toHaveTextContent('Clicked');
});
Snapshot Testing
This feature allows you to create snapshot tests for your stories. In this example, the `Primary` story from `Button.stories` is rendered, and a snapshot is created to ensure the component's output does not change unexpectedly.
import { render } from '@testing-library/react';
import { composeStories } from '@storybook/testing-react';
import * as stories from './Button.stories';
const { Primary } = composeStories(stories);
test('primary button snapshot', () => {
const { asFragment } = render(<Primary />);
expect(asFragment()).toMatchSnapshot();
});
@testing-library/react is a popular testing library for React applications. It focuses on testing components in a way that resembles how users interact with them. While it does not integrate directly with Storybook, it can be used alongside Storybook to test components.
Jest is a comprehensive testing framework for JavaScript applications. It includes features for running tests, mocking, and snapshot testing. Jest can be used to test React components, but it does not provide the same level of integration with Storybook as @storybook/testing-react.
Enzyme is a testing utility for React that allows you to manipulate, traverse, and simulate events on React components. It provides a different API compared to @storybook/testing-react and does not integrate directly with Storybook.
Testing utilities that allow you to reuse your stories in your unit tests
You are using Storybook for you 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.
@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.
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
This library requires you to be using Storybook's Component Story Format (CSF), which is the recommended way to write stories since Storybook 6.
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 { setGlobalConfig } from '@storybook/testing-react';
import * as globalStorybookConfig from './.storybook/preview'; // path of your preview.js file
setGlobalConfig(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 ./setup.js"
}
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 } 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 } 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', async () => {
const onClickSpy = jest.fn();
render(<Primary onClick={onClickSpy} />);
const buttonElement = screen.getByRole('button');
buttonElement.click();
expect(onClickSpy).toHaveBeenCalled();
});
@storybook/testing-react
is typescript ready and provides autocompletion to easily detect all stories of your component:
It also provides the props of the components just as you would normally expect when using them directly in your tests:
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',
};
FAQs
Testing utilities that allow you to reuse your stories in your unit tests
The npm package @storybook/testing-react receives a total of 123,760 weekly downloads. As such, @storybook/testing-react popularity was classified as popular.
We found that @storybook/testing-react demonstrated a not healthy version release cadence and project activity because the last version was released a year ago. It has 30 open source maintainers collaborating on the project.
Did you know?
Socket for GitHub automatically highlights issues in each pull request and monitors the health of all your open source dependencies. Discover the contents of your packages and block harmful activity before you install or update your dependencies.
Product
Socket now supports uv.lock files to ensure consistent, secure dependency resolution for Python projects and enhance supply chain security.
Research
Security News
Socket researchers have discovered multiple malicious npm packages targeting Solana private keys, abusing Gmail to exfiltrate the data and drain Solana wallets.
Security News
PEP 770 proposes adding SBOM support to Python packages to improve transparency and catch hidden non-Python dependencies that security tools often miss.