我正在尝试为需要在其componentWillMount
方法中完成异步操作的React组件编写测试。 componentWillMount
调用作为prop传递的函数,该函数返回promise,然后在测试中模拟该函数。
这可以正常工作,但是如果在调用setImmediate
或process.nextTick
的过程中测试失败,则Jest不会处理该异常,并且该异常会过早退出。在下面,您可以看到我什至试图捕获此异常,但无济于事。
我如何在Jest中使用setImmediate
或nextTick
之类的东西?对于这个问题,可以接受的答案是我尝试实现的失败: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
Node v6.9.1
最佳答案
另一个可能更干净的解决方案,使用异步/等待并利用笑话/摩卡(mocha)的能力来检测返回的 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);
});
关于node.js - Jest : tests can't fail within setImmediate or process. nextTick回调,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41792927/