我最近想測試某個自定義方法在React組件的componentDidMount
方法中有條件地調用。使用Jest窺視componentDidMount中的方法調用
componentDidMount() {
if (this.props.initOpen) {
this.methodName();
}
}
我用玩笑作爲我的測試框架,其中包括爲jest.fn()
嘲笑/間諜。我讀過,這將是相當瑣碎與興農測試,通過執行類似如下:
sinon.spy(Component.prototype, "methodName");
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
我試圖用玩笑來創建此像這樣:
Component.prototype.methodName = jest.fn();
const wrapper = mount(<Component {...props} />);
expect(wrapper.instance().methodName).toHaveBeenCalled();
此代碼失敗並引發以下錯誤:
jest.fn() value must be a mock function or spy.
Received:
function: [Function bound mockConstructor]
是否可以使用Jest測試此功能?如果是這樣,怎麼樣?
謝謝!看起來就在幾個月前剛剛出現在19.0.0。不能相信我在文檔中跳過了它。 – seansean11
歡迎您 – Jonathan
它會在組件中實際調用'methodName()'函數,還是隻是僞造它? – prime