[英]Testing with jest+enzyme, mock functions is called twice for no reason
[英]Testing with Jest+Enzyme API Mock calls is not beeing run
我有一個我無法理解的問題,我希望有人可以幫助我。
這是我的測試:state.messages是一個空數組,在要運行的函數中api.botReply被調用0次。
state.typing設置為true,所以我知道我運行了該函數。
test('test to resolve data from botReply', done => {
const wrapper = shallow(<Bot />);
api.botReply = jest.fn(() =>
Promise.resolve(wrapper.setState({ typing: false }))
);
wrapper.instance().sendReply();
setImmediate(() => {
wrapper.update();
console.log(wrapper.state('typing'));
console.log(wrapper.state('messages'));
expect(api.botReply).toHaveBeenCalledTimes(1);
done();
});
});
這是運行的功能:
sendReply = () => {
this.setState({ typing: true });
api.botReply()
.then(reply => {
this.setState({ messages: [...this.state.messages, reply], typing: false });
})
};
丟棄承諾鏈並使用隨機延遲會導致類似這樣的比賽條件。
由於在測試中提供了承諾,因此應將其鏈接起來以保持正確的控制流程。 將Jest間諜指定為方法不是一個好習慣,因為以后不會對其進行清理。 一個promise應該通過reply
來解決,而不是設置狀態。
應該是這樣的:
test('test to resolve data from botReply', async () => {
const wrapper = shallow(<Bot />);
const promise = Promise.resolve('reply')'
jest.spyOn(api, 'botReply').mockImplementation(() => promise);
wrapper.instance().sendReply();
expect(wrapper.state('typing')).toBe(true);
await promise;
expect(api.botReply).toHaveBeenCalledTimes(1);
expect(wrapper.state('typing')).toBe(false);
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.