Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock function not getting called in jest

I'm trying to test:

onChange(value) {
  this.setState({ postcode: value });
  if (value.length >= 3) this.listSuggestions(value);
}

by writing:

test("onChange updates the state", () => {
  const postalCodeWrapper = mount(<PostalCode />);
  const instance = postalCodeWrapper.instance();
  const listSuggestions = jest.fn(instance.listSuggestions);

  const mockValue = "this is mock value";
  instance.onChange(mockValue);
  expect(instance.state.postcode).toBe(mockValue);
  expect(listSuggestions).toHaveBeenCalled();
});

And this returns Expected mock function to have been called, but it was not called., talking about listSuggestions. Why is that? Same thing happens if I remove the if (value.length >= 3) statement.

like image 413
Xeen Avatar asked May 11 '26 06:05

Xeen


1 Answers

Your problem is this line:

const listSuggestions = jest.fn(instance.listSuggestions);

When you call that, jest.fn is returning a new function, not mutating the existing method. You assign it to a const, but your component will be calling the original.

Change it to:

instance.listSuggestions = jest.fn(instance.listSuggestions);

To overwrite the component method with the mock function, which it will then call assuming the conditional check passes.

like image 72
Jared Smith Avatar answered May 13 '26 21:05

Jared Smith