import { afterAll, afterEach, beforeAll, describe, expect, it, vi, } from 'vitest'; import { timeout } from './timeout.js'; describe('timeout', () => { describe('with real timers', () => { it('does not resolve in the current event loop', async () => { const winner = await Promise.race([ (async (): Promise => { await timeout(0); return 'timeout'; })(), (async (): Promise => { // nextTick runs immediately at the start of the next event loop await new Promise((resolve) => process.nextTick(resolve)); return 'nextTick'; })(), ]); expect(winner).toBe('nextTick'); }); it('resolves in the next event loop', async () => { const winner = await Promise.race([ (async (): Promise => { await timeout(0); return 'timeout'; })(), (async (): Promise => { // setImmediate will run all queued functions await new Promise((resolve) => setImmediate(resolve)); return 'setImmediate'; })(), ]); expect(winner).toBe('setImmediate'); }); }); describe('with fake timers', () => { beforeAll(() => { vi.useFakeTimers(); }); afterEach(() => { vi.clearAllTimers(); }); afterAll(() => { vi.useRealTimers(); }); it('does not resolve before given duration', async () => { const promise = timeout(100); vi.advanceTimersByTime(50); await expect(promise).toNeverResolve(); }); it('resolves after the given duration', async () => { const promise = timeout(100); vi.advanceTimersByTime(100); expect(await promise).toBeUndefined(); }); }); });