LoginSignup
1
0

More than 3 years have passed since last update.

emotionを用いたReactのプロジェクトでスナップショットテストをする

Last updated at Posted at 2021-03-28

前回書いた記事の少し発展です。

スタイルではなくclass名の変更が検知される

emotionを使って開発してるブロジェクトでstoryshotsを用いたスナップショットテストを行おうとすると、そのままだとスタイルではなくclass名がテストされてるという問題があります。(以下の画像参照)

css変更テストクラス名.png

画像を見るとわかるようにclass名の変更が検知されています。しかし、これはテストの意図としては間違っていて、スタイルの変更を検知して欲しいはずです。意外とこの辺ことについて書かれている記事がなかったので、今回はこの問題を解決する方法について紹介していきます。

環境というか諸々のバージョン

yarn -v
1.22.10

node -v
v14.11.0

react@16.13.1

@storybook/react@6.1.20

@storybook/addon-storyshots@6.1.2

などなど

解決方法

emotion/jestを導入します。

yarn add -D @emotion/jest

storyshotのテストのファイルに以下のように設定を追加します。

src/Storyshots.test.js
import initStoryshots, { multiSnapshotWithOptions } from '@storybook/addon-storyshots';
import { createSerializer } from '@emotion/jest';
initStoryshots({
  integrityOptions: { cwd: __dirname }, // it will start searching from the current directory
  test: multiSnapshotWithOptions(),
  snapshotSerializers: [createSerializer()], //これが大事
});

その上でテストを実行すると、

スナップショットテストスタイルの変更.png

上記の画像のように、スタイルの変更を検知してくれるようになります。

この記事が似たようなことで困っている方の助けになれば幸いです。

参考

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