import { withTimeout } from './with-timeout'; describe('withTimeout', () => { afterEach(() => { jest.useRealTimers(); }); it('resolves with the value when the promise settles in time', async () => { await expect(withTimeout(Promise.resolve(42), 1000, 'late')).resolves.toBe( 42, ); }); it('rejects with the original error when the promise rejects in time', async () => { await expect( withTimeout(Promise.reject(new Error('boom')), 1000, 'late'), ).rejects.toThrow('boom'); }); it('rejects with the given message when the promise takes too long', async () => { jest.useFakeTimers(); const pending = withTimeout( new Promise(() => undefined), 500, 'too slow', ); const assertion = expect(pending).rejects.toThrow('too slow'); await jest.advanceTimersByTimeAsync(500); await assertion; }); it('clears its timer once the promise settled', async () => { jest.useFakeTimers(); await withTimeout(Promise.resolve(1), 500, 'late'); expect(jest.getTimerCount()).toBe(0); }); });