假设我有my-file.ts
async function run() {
await new Promise(resolve => {
setTimeout(() => resolve(), 3000);
});
setTimeout(() => console.log('hello'), 5000);
}
export default run();我想用Jest来测试它。如果我这样做了:
it('should wait until all code has executed', async () => {
const start = new Date();
console.log('Waiting...', new Date());
await require('./my-file').default;
const stop = new Date();
console.log(`done after ${(stop.getTime() - start.getTime()) / 1000} s`);
});结果是:
console.log test/tmp.test.ts:3
Waiting... 2020-01-03T11:56:59.822Z
console.log test/tmp.test.ts:8
done after 3.009 s这是有道理的。但当我编译并运行my-file.ts时,节点等待所有超时清除,并且所有控制台日志都正确显示:
$ tsc my-file.ts && node my-file.js
hello
$我想重现Node的行为,即等待所有异步代码执行完毕。我怎么才能用jest做到这一点呢?
另外,谁能解释一下为什么下面的内容根本不需要等待?
it('should wait until all code has executed', async () => {
await require('./my-file');
});发布于 2020-01-03 21:44:44
问题是,您的Promise在3秒后执行resolves,并且运行来自jest的测试,因为您使用await require('./my-file').default;阻止执行,直到Promise为resolved或rejected。您的第二个超时只是在将运行的5秒之后向事件队列添加一个超时回调。
要复制等待5秒,请在第二个超时中解析Promise。此外,如果您返回新的promise,则不需要async/await。
function run() {
return new Promise(resolve => {
setTimeout(() => console.log('hello after 3 sec'), 3000);
setTimeout(() => resolve(), 5000);
});
}
export default run();https://stackoverflow.com/questions/59578384
复制相似问题