【问题标题】:How to spy on a mock function next.js jest RTL如何监视模拟函数 next.js jest RTL
【发布时间】: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


【解决方案1】:

我用窥探 useRouter 的方式解决它,并在创建模拟后渲染页面

    test.only("should redirect when form submitted with success", async () => {
        
         const useRouter = jest
          .spyOn(require("next/router"), "useRouter")
          .mockReturnValue({
            ...useRouterProps,
          });
        const routerReplace = jest.spyOn(useRouter(), "replace");
   
        render(<HomePage {...props} />);
        const submitBtn = screen.getByRole("button", {
          name: /submit/i,
        });

        userEvent.click(submitBtn);

        await waitFor(() => expect(routerReplace).toHaveBeenCalled());
      });

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-09-21
  • 2021-03-28
  • 1970-01-01
  • 2022-06-29
  • 2022-06-17
  • 1970-01-01
  • 2019-06-12
相关资源
最近更新 更多