开玩笑:在setImmediate或process.nextTick回调中测试不会失败 [英] Jest: tests can't fail within setImmediate or process.nextTick callback
问题描述
我正在尝试为需要在其componentWillMount
方法中完成异步操作的React组件编写测试. componentWillMount
调用作为prop传递的函数,该函数返回promise,然后在测试中模拟该函数.
I'm trying to write a test for a React component that needs to complete an asynchronous action in its componentWillMount
method. componentWillMount
calls a function, passed as a prop, which returns a promise, and I mock this function in my test.
这很好,但是如果在调用setImmediate
或process.nextTick
的过程中测试失败,则Jest不会处理该异常,并且该异常会过早退出.在下面,您可以看到我什至试图捕获此异常,但无济于事.
This works fine, but if a test fails in a call to setImmediate
or process.nextTick
, the exception isn't handled by Jest and it exits prematurely. Below, you can see I even try to catch this exception, to no avail.
我如何在Jest中使用setImmediate
或nextTick
之类的东西?对于这个问题,可以接受的答案是我尝试失败的实现:反应酶-测试`componentDidMount`异步调用.
How can I use something like setImmediate
or nextTick
with Jest? The accepted answer to this question is what I'm trying to implement unsuccessfully: React Enzyme - Test `componentDidMount` Async Call.
it('should render with container class after getting payload', (done) => {
let resolveGetPayload;
let getPayload = function() {
return new Promise(function (resolve, reject) {
resolveGetPayload = resolve;
});
}
const enzymeWrapper = mount(<MyComponent getPayload={getPayload} />);
resolveGetPayload({
fullname: 'Alex Paterson'
});
try {
// setImmediate(() => {
process.nextTick(() => {
expect(enzymeWrapper.hasClass('container')).not.toBe(true); // Should and does fail
done();
});
} catch (e) {
console.log(e); // Never makes it here
done(e);
}
});
笑话v18.1.0
节点v6.9.1
推荐答案
另一个可能更清洁的解决方案,使用async/await并利用jest/mocha的功能来检测返回的诺言:
Another potentially cleaner solution, using async/await and leveraging the ability of jest/mocha to detect a returned promise:
function currentEventLoopEnd() {
return new Promise(resolve => setImmediate(resolve));
}
it('should render with container class after getting payload', async () => {
let resolveGetPayload;
let getPayload = function() {
return new Promise(function (resolve, reject) {
resolveGetPayload = resolve;
});
}
const enzymeWrapper = mount(<MyComponent getPayload={getPayload} />);
resolveGetPayload({
fullname: 'Alex Paterson'
});
await currentEventLoopEnd(); // <-- clean and clear !
expect(enzymeWrapper.hasClass('container')).not.toBe(true);
});
这篇关于开玩笑:在setImmediate或process.nextTick回调中测试不会失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!