2017-04-06 23 views
10

我最近想測試某個自定義方法在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測試此功能?如果是這樣,怎麼樣?

回答

18

關鍵是使用笑話spyOn方法。它應該是這樣的:

const spy = jest.spyOn(Component.prototype, 'methodName'); 
const wrapper = mount(<Component {...props} />); 
wrapper.instance().methodName(); 
expect(spy).toHaveBeenCalled(); 

由於這裏找到如:Test if function is called react and enzyme

請注意,這也是每個測試運行

let spy 

afterEach(() => { 
    spy.mockClear() 
}) 

https://facebook.github.io/jest/docs/en/jest-object.html#jestclearallmocks

後清除暗中監視功能的最佳實踐
+0

謝謝!看起來就在幾個月前剛剛出現在19.0.0。不能相信我在文檔中跳過了它。 – seansean11

+0

歡迎您 – Jonathan

+0

它會在組件中實際調用'methodName()'函數,還是隻是僞造它? – prime

1

我知道它有點晚,但我遇到了這一點,並建議測試componentDidMount啓動呼叫您的嵌套的方法,你的測試應該是這個樣子:

模塊

componentDidMount() { 
    if (this.props.initOpen) { 
    this.methodName(); 
    } 
} 

測試 - 好

it('should call methodName during componentDidMount',() => { 
    const methodNameFake = jest.spyOn(MyComponent.prototype, 'methodName'); 
    const wrapper = mount(<MyComponent {...props} />); 
    expect(methodNameFake).toHaveBeenCalledTimes(1); 
}); 

如果你打電話componentDidMount那麼你的說法,methodNamecomponentDidMount稱爲更有效。

測試 - 錯誤

it('should call methodName during componentDidMount',() => { 
    const spy = jest.spyOn(Component.prototype, 'methodName'); 
    const wrapper = mount(<Component {...props} />); 
    wrapper.instance().methodName(); 
    expect(spy).toHaveBeenCalled(); 
} 

通過編寫測試這樣的 - 你調用該方法,然後斷言它被調用。當然它會給你一個叫它的東西。

+0

這些測試都不適用於我,無法完全通過 – Byrd

+0

您是否在傳遞組件所需的所有道具? – hloughrey

+0

最後得到它的工作,需要爲它創建一個實例,併爲我的間諜創建forceUpdate。 – Byrd

相關問題