const mockedLogin = jest.fn(() => Promise.resolve()); //does not work if implementation is done here: "cannot read then of undefined"
jest.mock("../../hooks/useAuth", () => {
return () => ({
login: mockedLogin,
});
});
test("submitting the form calls onSubmit with username and password", async () => {
mockedLogin.mockImplementation(() => Promise.resolve()); //works fine here
render(<Login />);
const username = "name";
const password = "i need no password";
await userEvent.type(screen.getByLabelText(/username/i), username);
await userEvent.type(screen.getByLabelText(/password/i), password);
await userEvent.click(screen.getByRole("button", { name: /submit/i }));
expect(mockedLogin).toHaveBeenCalledWith({
username,
password,
});
expect(mockedLogin).toHaveBeenCalledTimes(1);
});
I am trying to mock login function returned by a custom hook.
The login function returns a promise.
If I use mockImplementation
inside the test block it works fine but if I use it outside of the test block mockedLogin returns undefined.
Have you tried:
const mockedLogin = jest.fn().mockResolvedValue();