はじめに
Reactの自動テストでreact-rooter-domのLinkをクリックし、他ページに遷移させるテストを書いたのですが、上手くいかず困ったため記載します
問題
Linkをクリックしているが、ページ遷移できていない様
expect(jest.fn()).toHaveBeenCalledWith(...expected)
Expected: "/card/register"
Number of calls: 0
Ignored nodes: comments, script, style
<html>
<head />
<body>
<div />
</body>
</html>
101 | await userEvent.click(button);
102 | await waitFor(() => {
> 103 | expect(navigate).toHaveBeenCalledWith("/card/register");
| ^
104 | });
105 | });
106 | });
書いたテスト文
import '@testing-library/jest-dom';
import { render, screen } from '@testing-library/react';
import { MemoryRouter, Router, Route, Routes } from 'react-router-dom';
jest.mock('react-router-dom', () => ({
...jest.requireActual('react-router-dom'),
useNavigate: jest.fn(),
}));
describe("register_button_click", () => {
it("should navigate to register", async() => {
const navigate = jest.fn();
(useNavigate as jest.Mock).mockReturnValue(navigate);
await act(async() => {
render(
<MemoryRouter initialEntries={["/"]}>
<Routes>
<Route path="/" element={<Top />} />
</Routes>
</MemoryRouter>
);
});
const button = screen.getByTestId("register-button");
await userEvent.click(button);
await waitFor(() => {
expect(navigate).toHaveBeenCalledWith("/card/register");
});
});
});
原因
Linkでのページ遷移では、historyを見る必要がありそう
解決方法
import { createMemoryHistory } from 'history';
を利用し、テストを書き直し
import { createMemoryHistory } from 'history';
describe("register_button_click", () => {
it("should navigate to register", async() => {
const history = createMemoryHistory();
history.push = jest.fn()
await act(async() => {
render(
<Router location={history.location} navigator={history}>
<Routes>
<Route path="/" element={<Top />} />
</Routes>
</Router>
);
});
const button = screen.getByTestId("register-button");
await userEvent.click(button);
await waitFor(() => {
expect(history.push).toHaveBeenCalledWith(
{"hash": "", "pathname": "/card/register", "search": ""}, undefined, expect.any(Object)
);
});
});
});
参考