1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Storybookのファイル内play関数をJestでまとめて実行する

Last updated at Posted at 2024-07-15

大量のplay関数を一つ一つ実行するのが手間

Storybookのplay関数をJest側で実行する際にplay関数を一つ一つ選択して実行するのが手間だったため、ファイル内のplay関数まとめて実行するための共通処理を作ってみました。

Storybookのplay関数とJestを組み合わせたテスト手法に関しては以下の記事等で分かりやすくまとめられているため、こちらを参照してください。

今回の記事では上記の記事からさらに進んで、play関数をJest側からまとめて実行する手法を紹介します。

前提環境

  • react@17.0.2
  • @storybook/react@8.1.2
  • @storybook/types@8.1.2
  • @testing-library/react@12.1.2
  • jest@29.7.0

実際のコード

共通で使う関数

~/__test__/utils.tsx
import * as React from 'react'

import { composeStories, ReactRenderer } from '@storybook/react'
import { render } from '@testing-library/react'
import { ComposedStoryFn, Store_CSFExports } from '@storybook/types';

export const playStory = async (Story: ComposedStoryFn<ReactRenderer>) => {
  // wrapperは無しでもOK
  const { jestWrapper } = require('~/storybookPreview')
  const { container } = render(<Story />, { wrapper: jestWrapper })
  Story.play && await Story.play({ canvasElement: container })
}

export const playStories = (stories: Store_CSFExports<ReactRenderer>) => {
  const newStories: ComposedStoryFn<ReactRenderer>[] = Object.values(composeStories(stories))
  newStories.forEach((Story) => {
    // storyのnameをitに指定する
    it(Story.storyName, async () => {
      await playStory(Story)
    })
  })
}

使い方

specファイル内で以下のようにdescribeで囲って実行します。

Sample.spec.tsx
import { playStories } from '~/__test__/utils'
// 適当なstoryをimport
import * as sampleStories from '~/Sample.stories'

describe('SampleComponentTest', () => {
  playStories(sampleStories)
})

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?