Javascript 模拟函数没有在玩笑中被调用
我正在尝试测试:Javascript 模拟函数没有在玩笑中被调用,javascript,reactjs,unit-testing,jestjs,enzyme,Javascript,Reactjs,Unit Testing,Jestjs,Enzyme,我正在尝试测试: onChange(value) { this.setState({ postcode: value }); if (value.length >= 3) this.listSuggestions(value); } 以书面形式: test("onChange updates the state", () => { const postalCodeWrapper = mount(<PostalCode />); const instanc
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();
});
test(“onChange更新状态”,()=>{
const postalCodeWrapper=mount();
const instance=postalCodeWrapper.instance();
const listSuggestions=jest.fn(instance.listSuggestions);
const mockValue=“这是模拟值”;
onChange(mockValue);
expect(instance.state.postcode).toBe(mockValue);
expect(listSuggestions).tohaveBeenCall();
});
这将返回
预期已调用的模拟函数,但它未被调用。
,谈论列表建议。为什么呢?如果我删除if(value.length>=3)
语句,也会发生同样的情况。您的问题是这一行:
const listSuggestions = jest.fn(instance.listSuggestions);
调用该函数时,jest.fn
返回一个新函数,而不是改变现有方法。您将其分配给一个常量
,但您的组件将调用原始组件
将其更改为:
instance.listSuggestions = jest.fn(instance.listSuggestions);
使用mock函数覆盖组件方法,假设条件检查通过,它将调用该函数。不应该const listSuggestions=jest.fn(instance.listSuggestions)
beinstance.listSuggestions=jest.fn(instance.listSuggestions)
?@JaredSmith谢谢!成功了。