Using Storybook with React Testing Library: Story Reuse in Unit Tests
One of the biggest sources of test maintenance overhead is duplicated setup. You write a story for UserCard with a mock user object and decorator context, then write a separate Jest test that recreates the same mock user from scratch. When the User type changes, you update both.
Storybook's composeStories API eliminates this duplication. It lets you import a story into a test file, render it with all its args, decorators, and loaders applied, and assert against it with React Testing Library. One set of fixtures, used by both Storybook and your unit test suite.
This post covers composeStories, setProjectAnnotations, the render model, and patterns for sharing mock data across your codebase.
The Problem: Duplicated Setup
Here's what duplicated setup looks like without story reuse:
// UserCard.stories.tsx
export const AdminUser: Story = {
args: {
user: {
id: '123',
name: 'Jane Doe',
role: 'admin',
avatar: 'https://example.com/avatar.jpg',
createdAt: '2024-01-15',
},
},
};
// UserCard.test.tsx — recreating the same data
test('shows admin badge for admin users', () => {
render(
<UserCard
user={{
id: '123',
name: 'Jane Doe',
role: 'admin',
avatar: 'https://example.com/avatar.jpg',
createdAt: '2024-01-15',
}}
/>
);
expect(screen.getByText('Admin')).toBeInTheDocument();
});When you add a required field to User, you update the story. Then you track down every test file that constructs a User object manually and update those too. It's tedious and it scales badly.
composeStories: Rendering Stories in Tests
composeStories takes your story file's exports and returns components that are pre-configured with the story's args, decorators, and loaders. You render them with React Testing Library's render() as if they were normal React components.
Install the required package if you haven't already (it ships with @storybook/react):
npm install --save-dev @storybook/reactSet up the project annotations. This is a one-time setup that applies your global Storybook configuration (the preview.ts decorators and parameters) to tests run outside Storybook:
// src/setupTests.ts (or vitest.setup.ts)
import { setProjectAnnotations } from '@storybook/react';
import * as globalStorybookConfig from '../.storybook/preview';
setProjectAnnotations(globalStorybookConfig);Reference this file in your test configuration:
// vitest.config.ts
export default defineConfig({
test: {
setupFiles: ['./src/setupTests.ts'],
environment: 'jsdom',
},
});
// or jest.config.ts
module.exports = {
setupFilesAfterFramework: ['./src/setupTests.ts'],
testEnvironment: 'jsdom',
};Now import and compose stories in your tests:
// UserCard.test.tsx
import { render, screen } from '@testing-library/react';
import { composeStories } from '@storybook/react';
import * as stories from './UserCard.stories';
const { AdminUser, GuestUser, LoadingState } = composeStories(stories);
describe('UserCard', () => {
test('shows admin badge for admin users', () => {
render(<AdminUser />);
expect(screen.getByText('Admin')).toBeInTheDocument();
});
test('does not show admin badge for guest users', () => {
render(<GuestUser />);
expect(screen.queryByText('Admin')).not.toBeInTheDocument();
});
test('shows skeleton during loading', () => {
render(<LoadingState />);
expect(screen.getByRole('status')).toBeInTheDocument();
expect(screen.queryByText('Jane Doe')).not.toBeInTheDocument();
});
});The AdminUser, GuestUser, and LoadingState components already have the correct args, the global theme provider decorator from preview.ts, and any story-level decorators. You're asserting against the same configuration that runs in Storybook — no duplication, and changes to story args are automatically reflected in tests.
Overriding Args in Tests
composeStories returns components that accept props, just like the underlying component. You can override args to test variations without creating new stories:
const { Default } = composeStories(stories);
test('shows truncated name when name is very long', () => {
render(<Default user={{ ...Default.args?.user, name: 'A'.repeat(100) }} />);
expect(screen.getByTitle('A'.repeat(100))).toBeInTheDocument();
});Or use the args prop directly (Storybook merges it with the story's base args):
test('shows error state', () => {
render(<Default args={{ isError: true }} />);
expect(screen.getByRole('alert')).toBeInTheDocument();
});This pattern is useful for edge cases that don't warrant a dedicated story — you write the test without creating documentation noise.
Async Stories: play Functions and Loaders
If a story has a play function, composeStories doesn't run it automatically when you use React Testing Library's render(). The story just renders — you're responsible for the assertions. This is intentional: play functions are for Storybook's interaction testing; RTL tests are for unit assertions.
For stories with loaders (the async data-fetching hooks that run before render), composeStories does execute them:
// UserCard.stories.tsx
export const WithLoadedData: Story = {
loaders: [
async () => ({
user: await fetchUser('123'),
}),
],
render: (args, { loaded: { user } }) => (
<UserCard {...args} user={user} />
),
};
// UserCard.test.tsx
const { WithLoadedData } = composeStories(stories);
test('renders loaded user data', async () => {
render(<WithLoadedData />);
// Wait for async loader to resolve
await screen.findByText('Jane Doe');
expect(screen.getByText('jane@example.com')).toBeInTheDocument();
});Use findBy* queries (which wait for the element) when rendering stories with async loaders.
setProjectAnnotations in Detail
setProjectAnnotations is what applies your global Storybook configuration — the decorators and parameters in preview.ts — to tests running in Jest or Vitest. Without it, composeStories would render stories without any of the global providers, themes, or other context that Storybook applies automatically.
// .storybook/preview.ts
import { ThemeProvider } from 'styled-components';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { darkTheme } from '../src/theme';
const queryClient = new QueryClient();
export const decorators = [
(Story) => (
<QueryClientProvider client={queryClient}>
<ThemeProvider theme={darkTheme}>
<Story />
</ThemeProvider>
</QueryClientProvider>
),
];With setProjectAnnotations configured, stories rendered via composeStories in tests automatically get wrapped in the QueryClientProvider and ThemeProvider. Your tests that use TanStack Query or styled-components just work.
If you have multiple annotation files (e.g., an addon that adds its own preview file), pass them all:
import { setProjectAnnotations } from '@storybook/react';
import * as addonAnnotations from 'some-storybook-addon/preview';
import * as previewAnnotations from '../.storybook/preview';
setProjectAnnotations([addonAnnotations, previewAnnotations]);Sharing Mock Data
The real value of story reuse isn't just rendering — it's centralizing your mock data. Instead of scattering mock objects across test files, define them in a shared location that both stories and tests import:
// src/test-fixtures/users.ts
export const mockAdminUser = {
id: '123',
name: 'Jane Doe',
email: 'jane@example.com',
role: 'admin' as const,
avatar: 'https://example.com/jane.jpg',
createdAt: '2024-01-15T10:00:00Z',
permissions: ['read', 'write', 'delete', 'manage_users'],
};
export const mockGuestUser = {
id: '456',
name: 'Bob Smith',
email: 'bob@example.com',
role: 'guest' as const,
avatar: 'https://example.com/bob.jpg',
createdAt: '2024-03-20T14:30:00Z',
permissions: ['read'],
};// UserCard.stories.tsx
import { mockAdminUser, mockGuestUser } from '../test-fixtures/users';
export const AdminUser: Story = {
args: { user: mockAdminUser },
};
export const GuestUser: Story = {
args: { user: mockGuestUser },
};// UserCard.test.tsx — no duplication
import { mockAdminUser } from '../test-fixtures/users';
test('shows all admin permissions', () => {
render(<UserCard user={mockAdminUser} />);
mockAdminUser.permissions.forEach((permission) => {
expect(screen.getByText(permission)).toBeInTheDocument();
});
});When User type changes, you update test-fixtures/users.ts. Stories and tests both inherit the change.
MSW Handlers in Stories and Tests
If your stories use Mock Service Worker handlers, you can reuse those in Jest tests too. This is particularly useful for components that fetch their own data:
// UserProfile.stories.tsx
import { http, HttpResponse } from 'msw';
export const LoadedProfile: Story = {
parameters: {
msw: {
handlers: [
http.get('/api/users/123', () => {
return HttpResponse.json(mockAdminUser);
}),
],
},
},
};In Jest, set up MSW's Node server and import the same handlers:
// UserProfile.test.tsx
import { setupServer } from 'msw/node';
import { http, HttpResponse } from 'msw';
import { mockAdminUser } from '../test-fixtures/users';
// Import the handlers directly from where stories define them
import { handlers } from './UserProfile.handlers';
const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());
test('displays user profile after loading', async () => {
render(<UserProfile userId="123" />);
await screen.findByText('Jane Doe');
expect(screen.getByText('jane@example.com')).toBeInTheDocument();
});Extract handlers into a separate file that both the story's parameters.msw.handlers and the Jest test's setupServer can import. The network layer is defined once.
When composeStories Doesn't Fit
composeStories is the right tool when:
- You want to run assertions against a fully decorated component (with providers, themes, contexts)
- Your test is verifying behavior that's already represented in a story variant
- You want to eliminate duplicated mock data
Stick with direct render() calls when:
- You're testing a very specific prop combination that doesn't warrant a story
- You're testing a hook in isolation with
renderHook - The story's decorators add overhead you don't need for a fast unit test
- You're mocking module-level imports that conflict with Storybook's decorator system
Both approaches can coexist in the same test file. Use composeStories for the happy path and common variants, direct render() for edge cases.
A Note on Test Philosophy
composeStories doesn't change what you should be testing — it changes where you source the test setup from. Unit tests written with React Testing Library should still test behavior: user interactions, rendered output, state changes. They shouldn't test implementation details like component state variable names or internal method calls.
The combination of Storybook stories (for visual documentation and interaction tests) and React Testing Library unit tests (for behavior assertions) with composeStories bridging the two gives you a test suite that's both comprehensive and maintainable.
For the end-to-end layer — multi-page flows, real API calls, cross-component integration — HelpMeTest covers what component-level testing can't reach, running full browser tests against your deployed application and alerting you when user journeys break.
Summary
composeStories and setProjectAnnotations make story reuse in unit tests practical. Configure setProjectAnnotations once in your test setup file, then use composeStories in any test file to render stories with their full Storybook context. Combine this with centralized mock data in test-fixtures/ and shared MSW handlers to eliminate the duplication that makes test suites expensive to maintain.