Skip to content

Instantly share code, notes, and snippets.

@rstacruz
Last active April 7, 2025 02:03
Show Gist options
  • Save rstacruz/4e301b59a1c9642ecdca1e63dc210bfd to your computer and use it in GitHub Desktop.
Save rstacruz/4e301b59a1c9642ecdca1e63dc210bfd to your computer and use it in GitHub Desktop.
Test storybook stories in Vitest + React testing library

Test storybook stories in Vitest + React testing library

Let's say you have these files:

  • Chat.tsx
  • Chat.stories.tsx
  • Chat.test.tsx

The test file can be written to use Storybook stories:

import { describe, it } from 'vitest'
import { render, screen } from '@testing-library/react'
import * as stories from './Chat.stories'

const Component = stories.default.component

// Example: making assertions on certain stories
describe('story: Primary', () => {
  it('render with assertions', () => {
    const story = stories.Primary

    render(<Component {...story.args} />)

    // Check at least one chat message exists
    const chatMessages = screen.getAllByRole('article', { hidden: true })
    expect(chatMessages.length).toBeGreaterThan(0)
  })
})


// Example: render storybook stories via React testing-library
describe('all stories', () => {
  const storyEntries = Object.entries(stories).filter(
    ([key, story]) =>
      typeof story === 'object' && key !== 'default' && 'args' in story
  )

  it.each(storyEntries)(
    'renders %s story without errors',
    (_storyName, story) => {
      if (!('args' in story)) throw new Error('Invariant')

      render(<Component {...story.args} />)
    }
  )
})

Why

  • Storybook stories can act like smoke tests. Tests will fail if there are any stories that emit errors on render.
  • Test stories can be inspected visually in Storybook.

Also see

  • Vitest browser mode takes this idea one step further and removes the need for Storybook (at least for this use case).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment