Home > Software design >  How to spy on a mock function next.js jest RTL
How to spy on a mock function next.js jest RTL

Time:12-03

I am trying to mock replace function which is in useRouter() hook from next/router my mocks and tests looks like this:

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

I can see in console that it has been called but the test doesn't pass.

CodePudding user response:

I resolve it the way that I spyon useRouter , and render page after creating mocks

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

  • Related