LoginSignup
3
3

More than 3 years have passed since last update.

storybookのstoryshotとemotionでsnapshotテストする方法

Posted at

経緯:runner_tone4:

storybookのstoryshotでsnapshotテストを導入しました。
そこでemotionを使っていて、この子がランダムなクラス名を自動生成してくれるのですが、実際に適応されるcssが同じでもクラス名が以下のように変わってたり変わってなかったりします(ロジックまでは見てないので、どうして同じパターンもあるのかはわからない)。

exports[`Storyshots button 1`] = `
<button
  className="css-z0t02t-Button ej1mrh80"
  type="button"
>
  button
</button>
`;

これではテストごとに失敗する可能性があり、失敗した理由がわからないのでテストの意味があまりない。。。:cry:
で、いい方法はないかな〜と思ってやってみました。

設定方法:pencil2:

storyshotを入れていない人は、まずreadmeに従って設定してください。

jest-emotionを使います。

npm install --save-dev jest-emotion

initStoryshots()を以下のように修正

import initStoryshots from '@storybook/addon-storyshots';
import serializer from 'jest-emotion';

initStoryshots({
  snapshotSerializers: [serializer]
} as any);

でsnapshotを作成すると

exports[`Storyshots button 1`] = `
.emotion-0 {
  margin-right: 16px;
}
<button
  className="emotion-0 emotion-1"
  type="button"
>
  button
</button>
`;

これでクラス名は固定されて、スタイルの差分がでるので確認しやすくなりました:sunny:
他にいい方法もありそうな気がしているので、知ってたら教えてくださいm(_ _)m

initStoryshotsでオブジェクトをanyにしてるわけ。

ドキュメントにはsnapshotSerializersがoptionとして載っているのですが、型定義には以下のようになっています。(2019/08/26現在)

export interface InitOptions<Rendered = any> {
    configPath?: string;
    suite?: string;
    storyKindRegex?: RegExp;
    storyNameRegex?: RegExp;
    framework?: string;
    test?: Test;
    renderer?: (node: JSX.Element) => Rendered;
    serializer?: (rendered: Rendered) => any;
    integrityOptions?: {};
}

となっているので、anyで逃げました:sweat_smile:

https://github.com/storybookjs/storybook/tree/master/addons/storyshots/storyshots-core#snapshotserializers

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