gpt4 book ai didi

node.js - Jest : tests can't fail within setImmediate or process. nextTick 回调

转载 作者:搜寻专家 更新时间:2023-10-31 22:39:02 24 4
gpt4 key购买 nike

我正在尝试为需要在其 componentWillMount 方法中完成异步操作的 React 组件编写测试。 componentWillMount 调用一个函数,作为 prop 传递,它返回一个 promise ,我在测试中模拟了这个函数。

这工作正常,但如果测试在调用 setImmediateprocess.nextTick 时失败,则 Jest 不会处理异常,它会提前退出。在下面,您可以看到我什至 try catch 此异常,但无济于事。

如何在 Jest 中使用 setImmediatenextTick 之类的东西?这个问题的公认答案是我试图实现但未成功的: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);
}
});

Jest v18.1.0

Node v6.9.1

最佳答案

另一个可能更清洁的解决方案,使用 async/await 并利用 jest/mocha 的能力来检测返回的 promise :

// async test utility function
function currentEventLoopEnd() {
return new Promise(resolve => setImmediate(resolve));
}

it('should render with container class after getting payload', async () => {

// mock the API call in a controllable way,
// starts out unresolved
let resolveGetPayload; // <- call this to resolve the API call
let getPayload = function() {
return new Promise(function (resolve, reject) {
resolveGetPayload = resolve;
});
}

// instanciate the component under state with the mock
const enzymeWrapper = mount(<MyComponent getPayload={getPayload} />);
expect(enzymeWrapper.hasClass('container')).not.toBe(true);

resolveGetPayload({
fullname: 'Alex Paterson'
});

await currentEventLoopEnd(); // <-- clean and clear !

expect(enzymeWrapper.hasClass('container')).toBe(true);
});

关于node.js - Jest : tests can't fail within setImmediate or process. nextTick 回调,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41792927/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com