How to flush promises since Jest 26+

t98cgbkg  于 2023-09-28  发布在  Jest
关注(0)|答案(1)|浏览(118)

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();
    }
}

带有遗留伪计时器的测试1(通过):

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');
    });
});

使用现代伪计时器的测试2(失败)

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毫秒。**在调试期间,它在await new Promise(process.nextTick)上冻结

dhxwm5r4

dhxwm5r41#

在我的测试中,我使用了你描述的flushPromises方法:

const flushPromises = () => new Promise(setImmediate);

但是为了使这个工作,我必须导入setImmediate

import { setImmediate } from 'timers';

相关问题