2017-01-04 141 views
4

酶文檔的完整DOM渲染here包含興農的生命週期方法的間諜下面的例子:如何用Jest和Enzyme模擬React組件生命週期方法?

describe('<Foo />',() => { 

    it('calls componentDidMount',() => { 
    sinon.spy(Foo.prototype, 'componentDidMount'); 
    const wrapper = mount(<Foo />); 
    expect(Foo.prototype.componentDidMount.calledOnce).to.equal(true); 
    }); 
}); 

什麼是相當於從玩笑此使用模擬功能?

我正在使用Create-React-App,並且如果可以用Jest實現相同的功能,則寧願不包括Sinon。

這就是我所期待的測試看起來像:

describe('<App />',() => { 

    it('calls componentDidMount',() => { 
    jest.fn(App.prototype, 'componentDidMount'); 
    const wrapper = mount(<App />); 
    expect(App.prototype.componentDidMount.mock.calls.length).toBe(1); 
    }); 
}); 

在這種情況下,App.prototype.componentDidMount不引用相同功能的間諜,因爲它會與興農做。

關於如何模擬功能實際工作的Jest文檔有點有限。我已經圍繞jest.fn()所做的討論here進行了討論,但它似乎並不等同於sinon.spy()。

我該如何使用Jest複製該測試?

+0

您正試圖測試React生命週期方法是否被調用?你爲什麼想這麼做?這應該是React本身的測試用例。您應該嘗試在生命週期方法中測試您正在調用的功能。這個測試對您的應用程序沒有任何價值。 –

回答

1

因爲jest.fn只有一個實現參數,所以這種方法不適用於這種方式。但更重要的是,你不應該窺視你想測試的對象的內部。你應該將Foo想象成一個黑盒子,你可以在其中放入一些屬性並獲得一些回饋。然後你意識到沒有必要測試Foo的內部函數,如componentDidMount,被調用。唯一重要的是黑盒的輸出。

但如果你真的想反正做測試:

const spy = jest.fn() 
const componentDidMount = Foo.prototype.componentDidMount 
Foo.prototype.componentDidMount = function(){ 
    spy() 
    componentDidMount() 
} 
1

由於玩笑19,你可以這樣做:

describe('<App />',() => { 
    it('calls componentDidMount',() => { 
    const spy = jest.spyOn(App.prototype, 'componentDidMount'); 
    const wrapper = mount(<App />); 
    expect(spy).toHaveBeenCalled(); 
    spy.mockReset(); 
    spy.mockRestore(); 
    }); 
}); 

jest.spyOn返回與所有一般可用的方法,如mock functionmockClearmockResetmockRestore

請確保在使用酶的mount或使用react-test-renderer的create之前設置您的間諜,以便創建的實例具有對被窺探的模擬函數的引用。

相關問題