[英]Mock function not getting called in jest
我正在嘗試測試:
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)
語句, if (value.length >= 3)
發生同樣的事情。
您的問題是這一行:
const listSuggestions = jest.fn(instance.listSuggestions);
當您調用它時, jest.fn
返回一個新函數,而不改變現有方法。 您將其分配給const
,但是您的組件將調用原始對象。
更改為:
instance.listSuggestions = jest.fn(instance.listSuggestions);
要使用模擬功能覆蓋組件方法,然后在條件檢查通過的情況下調用該方法。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.