Jest 26发布了一个基于@sinonjs/ fake timers的伪计时器的新实现。
以前我用过const flushPromises = () => new Promise(setImmediate);
现在我正试着用
await new Promise(process.nextTick);
正如这里所描述的:How to make Jest wait for all asynchronous code to finish execution before expecting an assertion,但在某些情况下它不起作用。
示例代码不工作时(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');
});
});
现代假计时器的Test2 (失败)
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');
});
});
引发的失败:“超过5000 ms的测试超时。在调试期间冻结在await new Promise(process.nextTick)
上。
发布于 2022-05-03 15:27:17
在我的测试中,我使用了您描述的flushPromises方法
const flushPromises = () => new Promise(setImmediate);
但是为了使这个工作,我必须导入setImmediate
import { setImmediate } from 'timers';
https://stackoverflow.com/questions/71942029
复制相似问题