Unknown developer
Unknown developer

Reputation: 5920

Jest test fails due to mock function despite its execution

The following Jest unit test:

const onSuccess = jest.fn(() => console.log("Boooboooo"));
render(
  <Footer onSuccess={onSuccess}
  />
);
const approveButton = screen.getByRole("button", {name: "APPROVE"});
userEvent.click(approveButton);
expect(onSuccess).toHaveBeenCalled();

fails:

expect(jest.fn()).toHaveBeenCalled()

Expected number of calls: >= 1
Received number of calls:    0

whereas onSuccess does run:

console.log
Boooboooo

The last two parts are from Jest logs. Any idea what's the issue?

Upvotes: 0

Views: 433

Answers (1)

hoangdv
hoangdv

Reputation: 16127

It seems the onSuccess function be called asynchronous, this means the assertion function is called before onSuccess function is called.

Let’s try to use waitFor helper to assert the callback function is called:

userEvent.click(approveButton);
await waitFor(() => expect(onSuccess).toHaveBeenCalled());

Upvotes: 1

Related Questions