【发布时间】:2021-11-27 17:41:31
【问题描述】:
我正在尝试从 next/router 模拟 useRouter() 钩子中的 replace 函数
我的模拟和测试看起来像这样:
jest.mock("next/router", () => ({
useRouter() {
return {
route: "/",
pathname: "",
locale: "pl",
replace: jest
.fn()
.mockImplementation((obj) => console.log("have been called", obj)),
};
},
}));
const routerReplace = jest.spyOn(useRouter(), "replace");
test.only("should redirect when form submitted with success", async () => {
render(<HomePage {...props} />);
const routerReplace = jest.spyOn(useRouter(), "replace");
const submitBtn = screen.getByRole("button", {
name: /submit/i,
});
userEvent.click(submitBtn);
//doesn't work
await waitFor(() => expect(routerReplace).toHaveBeenCalled());
// I tried also this
//await waitFor(() =>
// expect(useRouter().replace).toHaveBeenCalledTimes(1)
//);
});
我可以在控制台中看到它已被调用,但测试没有通过。
【问题讨论】:
-
这能回答你的问题吗? How to test Router.push with Jest/React
-
不完全是,一个解决方案是关于路由器,另一个使用 Typescript,但我想通了
-
忽略第二个答案使用 TypeScript 的事实,这个概念可以用来解决你的问题。
标签: unit-testing jestjs next.js react-testing-library