admin管理员组文章数量:1356337
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.
本文标签: javascriptMock function not getting called in jestStack Overflow
版权声明:本文标题:javascript - Mock function not getting called in jest - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743983113a2571165.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论