はじめに
初めまして!
エンジニアになって数年、今まで本を読むだけでしたが、もっとプライベートで楽しみながら成長したい!自分が学んだ足跡を残していきたい!と思い記事を書きました!
最終的には自在に開発できるようになりたいと思っています。
いろいろな記事を参考にさせてもらっています。
「いいね」か「ブックマーク」
を頂けると僕のモチベーションアップになります!
少しでも気に入っていただけたらよろしくお願いいたします!
今回の目的
自分の作ったコンポーネントを確認したり検証するための技術を身に付けたい!
公式のクイックスタートを参考に進めていきます。
項目ごとに補足のみ書いて進めています。わかりづらいところの理解の手助けになれば幸いです!
前回
主に参考にさせていただいた記事
バージョン
React-18.2
Storybook-8.1.4
Interaction tests
動作テストを行う。
・fireEvent
クリックや入力などのユーザーの動作をシミュレートするためのものです。
import { fireEvent } from '@storybook/test';
fireEvent.click(buttonElement);
fireEvent.change(inputElement, { target: { value: 'new value' } });
・waitFor
非同期処理の動作を待つためのもの。
import { waitFor } from '@storybook/test';
await waitFor(() => {
expect(someElement).toBeInTheDocument();
});
・within
コンテナ内の要素を探し、対象として選択できるようにする。canvasElementと併用すると全体のDOM情報を取得できる。
import { within } from '@storybook/test';
const container = within(someElement);
expect(container.getByText('some text')).toBeInTheDocument();
・waitForElementToBeRemoved
要素が削除されるまで順次処理を止める。
import { waitForElementToBeRemoved } from '@storybook/test';
await waitForElementToBeRemoved(() => document.querySelector('.loading-spinner'));
storyBook内のテストケースに記述します。
export const Default = {
parameters: {
...
},
play: async ({ canvasElement }) => {
// storyBookのcanvas取得
const canvas = within(canvasElement);
// data-testid="loading"で登録したところを確認して消えたら次の処理
await waitForElementToBeRemoved(await canvas.findByTestId('loading'));
// 内部のクリック処理が完全に終わるまで待機
await waitFor(async () => {
await fireEvent.click(canvas.getByLabelText('pinTask-1'));
await fireEvent.click(canvas.getByLabelText('pinTask-3'));
});
},
};
Automate tests with the test runner
全てのstoryテストの自動化
npm i --dev @storybook/test-runner
package.jsonにscriptコマンドを追加
{
"scripts": {
"test-storybook": "test-storybook"
}
}
実行した際に下記のエラーが出たら
コマンド実行し、ブラウザエンジンを操作するplaywrightをインストールする。
npx playwright install
テスト実行
npm run test-storybook --watch
次
Deploy Storybook