我正在尝试测试:
onChange(value) {
this.setState({ postcode: value });
if (value.length >= 3) this.listSuggestions(value);
}
通过写作:
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();
});
这会返回 Expected mock function to have been called, but it was not called.
,谈论listSuggestions
。这是为什么?如果我删除 if (value.length >= 3)
语句,也会发生同样的事情。
最佳答案
你的问题是这一行:
const listSuggestions = jest.fn(instance.listSuggestions);
当您调用它时,jest.fn
返回一个新 函数,而不是改变现有方法。您将其分配给 const
,但您的组件将调用原始组件。
将其更改为:
instance.listSuggestions = jest.fn(instance.listSuggestions);
用模拟函数覆盖组件方法,假设条件检查通过,它将调用该函数。
关于javascript - 模拟函数没有被 Jest 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54691539/