経緯
storybookのstoryshotでsnapshotテストを導入しました。
そこでemotionを使っていて、この子がランダムなクラス名を自動生成してくれるのですが、実際に適応されるcssが同じでもクラス名が以下のように変わってたり変わってなかったりします(ロジックまでは見てないので、どうして同じパターンもあるのかはわからない)。
exports[`Storyshots button 1`] = `
<button
className="css-z0t02t-Button ej1mrh80"
type="button"
>
button
</button>
`;
これではテストごとに失敗する可能性があり、失敗した理由がわからないのでテストの意味があまりない。。。
で、いい方法はないかな〜と思ってやってみました。
設定方法
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>
`;
これでクラス名は固定されて、スタイルの差分がでるので確認しやすくなりました
他にいい方法もありそうな気がしているので、知ってたら教えてください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で逃げました