propsで渡すものによってはモックを使ったりする場合もあるかと思いますが、propsで渡した値自体のテストを作りたい場合もあるかと思います。
propsでlistを渡すケース
Reactではlistはmapなどを使って表示させることが普通です。下記のように記述します。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
import React from "react"; import { render, screen } from "@testing-library/react"; import List from "./List"; describe("propsで値が渡っているか", () => { it("しかるべき値が渡っているかテスト", () => { const data = [ { id: 1, item: "テスト" }, { id: 2, item: "テスト1" }, { id: 3, item: "テスト2" }, ]; render(<List lists={data} />); const Items = screen .getAllByRole("listitem") .map((ele) => ele.textContent); const propsItems = data.map((ele) => ele.item); expect(Items).toEqual(propsItems); }); }); |
また、下記のようなテストケースも追加で作成するとなお良いでしょう。
- propsの値を渡さない場合
- propsの値が不正な値だった場合
propsに渡す関数をモック化する。
propsで渡す関数をモック化してそれが呼ばれているかのテスト
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
describe("渡した関数が呼ばれているか", () => { it("渡した関数が呼ばれないこと", () => { const kansu = jest.fn(); render(<Input kansu={kansu} />); userEvent.click(screen.getAllByRole("button")[0]); //コンポーネントでモック関数が呼ばれないための何かしらのuserEvent expect(kansu).not.toHaveBeenCalled(); }); it("渡した関数が一度呼ばれること", () => { const kansu = jest.fn(); render(<Input kansu={kansu} />); userEvent.click(screen.getAllByRole("button")[1]); //コンポーネントでモック関数を呼ぶための何かしらのuserEvent expect(kansu).toHaveBeenCalledTimes(1); }); }); |
jest.fn();
jestのモック関数です。何も機能を持たない関数になります。
expect(kansu).not.toHaveBeenCalled();
モック関数が呼ばれていないことをチェックできます。
expect(kansu).toHaveBeenCalledTimes(1);
モック関数が呼ばれていることをチェックできます。引数はモックが呼ばれた回数になります。
React Hooksのテスト
コンポーネントとは切り離してReact Hooks単体のテストも行うことができます。
インストール
1 2 |
npm i @testing-library/react-hooks npm i react-test-renderer |
テストコード
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
import { 作ったコンポーネント } from "./作ったコンポーネント"; import { act, renderHook } from "@testing-library/react-hooks"; import { cleanup } from "@testing-library/react"; afterEach(() => cleanup()); describe("Hooksのテスト", () => { it("テストケース", () => { const { result } = renderHook(() => コンポーネント(初期値)); expect(result.current.値(useStateなど)).toBe(初期値); act(() => { result.current.コンポーネント内の関数(); }); expect(result.current.値(useStateなど)).toBe(処理結果); } } |
result.current
これでコンポーネント内のstateの値や、関数などにアクセスすることが可能になります。
この記事へのコメントはありません。