個別のReducerのみをテストする場合
通常の例
1 2 3 4 5 6 7 8 9 10 11 12 13 |
import reducer from "../src/スライスのパス"; describe("xxx action", () => { let initialState = { mode: 0, value: 1, }; it("テストケース1", () => { const action = { type: xxx }; const state = reducer(initialState, action); expect(state.value).toEqual(2); }); } |
ExtraReducerの場合
非同期の結果が失敗した場合と成功した場合などで様々なケースでテストケースを記述することが可能です。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
import reducer, { 非同期の関数, } from "../src/スライス"; describe("extraReducers", () => { const initialState = { mode: 0, value: 0, }; it("fulfiledの場合", () => { const action = { type: 非同期の関数.fulfilled.type, payload: 1 }; const state = reducer(initialState, action); expect(state.value).toEqual(xxx); }); it("rejectedの場合", () => { const action = { type: 非同期の関数.rejected.type, payload: 2 }; const state = reducer(initialState, action); expect(state.value).toEqual(yyy); }); }); |
コンポーネントとの結合テストをする場合
以下のようにテストケースごとにstoreを生成し、テスト対象のコンポーネントをラップします。そうすることでReduxとコンポーネントの結合テストを行うことが可能になります。ちなみに、Reduxのstoreをテストコード側で作る場合はRedux側のinitialStateが適用されているので、テストコード側でinitialStateを用意する必要がないです。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 |
import React from "react"; import { render, screen, cleanup } from "@testing-library/react"; import userEvent from "@testing-library/user-event"; import { Provider } from "react-redux"; import テスト対象のコンポーネント from "./テスト対象のコンポーネント"; import { configureStore } from "@reduxjs/toolkit"; import 個別のReducer from "../src/個別のslice"; afterEach(() => { cleanup(); }); describe("Reduxとコンポーネントの結合テスト", () => { let store; beforeEach(() => { store = configureStore({ reducer: { 個別のReducer, }, }); }); it("任意のテスト", () => { render( <Provider store={store}> <テスト対象のコンポーネント /> </Provider> ); userEvent.click(screen.getByText("xxx")); expect(screen.getByTestId("yyyy")).toHaveTextContent(3); }); |
この記事へのコメントはありません。