如何监视模拟函数 next.js jest RTL

How to spy on a mock function next.js jest RTL

我正在尝试模拟 replace 函数,它位于 next/routeruseRouter() 钩子中 我的模拟和测试看起来像这样:

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)
         //);
      });

我可以在控制台中看到它已被调用,但测试没有通过。

我用窥探 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());
      });