LoginSignup
0
0

More than 1 year has passed since last update.

お手軽にロジックとStoryshotsのテストを分離する(Create React App)

Last updated at Posted at 2022-02-09

はじめに

Create React Appで作成したReactアプリにてnpm run testを実行すると、Storyshotsとロジックのテストが同時に実行されてしまいます。

それぞれのテストを分けて実行しようと思い調べてみるとjest.config.jsやbabelの設定が必要となり、思っていた以上に手間だったので、もっとお手軽な方法を備忘録してメモしておきます。

確認環境

react: v17.0.2
react-scripts: v5.0.0
yarn: v1.22.17

実施内容

storyshotsのためのtestファイルを作成

storyshots.test.ts
import initStoryshots from '@storybook/addon-storyshots';

initStoryshots({});

ここでは特にオプション等は指定しません。

ロジックだけをテストするコマンド

yarn react-scripts test --watchAll=false --testPathIgnorePatterns=src/storyshots.test.ts

Jest CLIオプションのtestPathIgnorePatternsを使用してtest実行時に
Storyshotsの設定ファイルを無視するようにします。

Storyshots単体でテストを実行するコマンド

yarn react-scripts test storyshots.test.ts

Storyshotsの設定ファイルだけが実行されるように指定します。

最終的なpackage.jsonの設定

  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --watchAll=false --testPathIgnorePatterns=src/storyshots.test.ts",
    "eject": "react-scripts eject",
    "storybook": "start-storybook -p 6006 -s public",
    "storyshots": "react-scripts test storyshots.test.ts",
    "storyshots-update": "react-scripts test --watchAll=false --update-snapshot storyshots.test.ts",
    "build-storybook": "build-storybook -s public"
  }

Storyshotsのupdateコマンドも含めて上記のようにするのが良いのかと思います。

注意 簡易的な方法なので、watchモード等でテストを再実行するとロジック、Storyshots両方のテストが実行されてしまうのでご注意ください。

0
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
0
0