自从开玩笑26&#x2B以来,如何冲洗承诺。
Jest 26根据 @Sinonjs/Fake-Timers运行了新的假计时器实施。
以前我用过
const flushPromises =()=>新的Promise(setimMediate);
现在,我试图用
等待新的Promise(Process.nexttick);
,如下所述: 但这在某些情况下不起作用。
示例代码在不起作用时(JEST版本:27.5.1):
class SuperFetch {
public static async get(): Promise<string> {
return 'never mind';
}
}
class ClassForTest {
public async get(): Promise<string> {
return SuperFetch.get();
}
}
带有旧式假计时器的Test1:
jest.useFakeTimers('legacy');
describe('Test', () => {
const flushPromises = (): Promise<void> => new Promise(setImmediate);
test('should flush promise', async () => {
SuperFetch.get = jest.fn().mockResolvedValue('test');
const instance = new ClassForTest();
let result;
instance.get().then(x => {
result = x;
});
jest.advanceTimersByTime(1000);
await flushPromises();
expect(result).toBe('test');
});
});
带有现代假计时器(失败)
jest.useFakeTimers('modern');
describe('Test', () => {
test('should flush promise', async () => {
SuperFetch.get = jest.fn().mockResolvedValue('test');
const instance = new ClassForTest();
let result;
instance.get().then(x => {
result = x;
});
jest.advanceTimersByTime(1000);
await new Promise(process.nextTick);
expect(result).toBe('test');
});
});
失败的 Test2
投掷:“测试超过5000毫秒的超时。
在调试期间,它会在上冻结,等待新的Promise(Process.nexttick)
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
对于我的测试,我正在使用您所描述的
flushpromises
方法:但是要使这项工作我必须导入
setimmediate
:For my test I am using the
flushPromises
method as you described:but to make this work I had to import
setImmediate
: