【发布时间】:2020-01-03 21:44:43
【问题描述】:
假设我有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 的行为,即等待所有异步代码执行。我怎么能开玩笑呢?
另外,谁能解释一下为什么下面的内容根本不等待?
it('should wait until all code has executed', async () => {
await require('./my-file');
});
【问题讨论】: