[英]Testing with Jest+Enzyme API Mock calls is not beeing run
I have a problem that I can't understand and I was hoping that someone could help me with. 我有一个我无法理解的问题,我希望有人可以帮助我。
This is my test: state.messages is an empty array and api.botReply is called 0 times when it is in the function to be ran. 这是我的测试:state.messages是一个空数组,在要运行的函数中api.botReply被调用0次。
state.typing is set to true so I know I run the function. 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();
});
});
And this is the function that is run: 这是运行的功能:
sendReply = () => {
this.setState({ typing: true });
api.botReply()
.then(reply => {
this.setState({ messages: [...this.state.messages, reply], typing: false });
})
};
Discarding promise chains and using random delays can lead to race conditions like this one. 丢弃承诺链并使用随机延迟会导致类似这样的比赛条件。
Since a promise is provided in tests, it should be chained to maintain correct control flow. 由于在测试中提供了承诺,因此应将其链接起来以保持正确的控制流程。 It's not a good practice to assign Jest spies as methods because they won't be cleaned up afterwards.
将Jest间谍指定为方法不是一个好习惯,因为以后不会对其进行清理。 A promise is supposed to resolve with
reply
, not set state. 一个promise应该通过
reply
来解决,而不是设置状态。
It should be something like: 应该是这样的:
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.