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.
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.
-
1
Shouldn't
const listSuggestions = jest.fn(instance.listSuggestions)
beinstance.listSuggestions = jest.fn(instance.listSuggestions)
? – Jared Smith Commented Feb 14, 2019 at 13:30 - 1 @JaredSmith thank you! That worked. – Xeen Commented Feb 14, 2019 at 13:33
1 Answer
Reset to default 5Your 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 ponent will be calling the original.
Change it to:
instance.listSuggestions = jest.fn(instance.listSuggestions);
To overwrite the ponent method with the mock function, which it will then call assuming the conditional check passes.