我有一个这样的测试失败了,因为没有调用模拟,问题是模拟被调用但在测试完成之前。
test('should submit if proper values', () => {
const spy = jest.fn().mockReturnValue({
data: {
authenticateUser: {
id: 123,
token: 'lol'
}
}
});
mountedWrapper.setProps({
loginMutation: spy
});
expect(spy).not.toHaveBeenCalled();
email.simulate('change', {
target: { name: 'username', value: 'email@test.com' }
});
password.simulate('change', {
target: { name: 'password', value: 'secret' }
});
form.simulate('submit');
expect(spy).toHaveBeenCalled();
});
但是,如果我添加以下 setTimeout,我可以让测试通过
setTimeout(() => {
expect(spy).toHaveBeenCalled();
}, 0);
不过,我正在寻找一种更好的方法来解决上述问题。有没有没有 setTimeout 的解决方案?
最佳答案
看起来您正在尝试测试一些异步代码。你读了吗this ?在 callbacks
部分,您可以找到:
By default, Jest tests complete once they reach the end of their execution. That means this test will not work as intended:
// Don't do this!
test('the data is peanut butter', () => {
function callback(data) {
expect(data).toBe('peanut butter');
}
fetchData(callback);
});
The problem is that the test will complete as soon as fetchData completes, before ever calling the callback. There is an alternate form of test that fixes this. Instead of putting the test in a function with an empty argument, use a single argument called done. Jest will wait until the done callback is called before finishing the test.
test('the data is peanut butter', done => {
function callback(data) {
expect(data).toBe('peanut butter');
done();
}
fetchData(callback);
});
If done() is never called, the test will fail, which is what you want to happen.
这是回调
的例子,但你也可以使用promises , .resolves/.rejects , 和 async/await .
关于reactjs - 开 Jest 如何等待基于模拟事件调用模拟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49435576/