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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With