1import { delayAsync, resolveWithTimeout, waitForActionAsync } from '../delay'; 2 3afterEach(() => { 4 jest.useRealTimers(); 5}); 6 7describe(delayAsync, () => { 8 it(`await for a given duration of milliseconds`, async () => { 9 jest.useFakeTimers(); 10 const promise = delayAsync(100); 11 jest.advanceTimersByTime(100); 12 await promise; 13 }); 14}); 15 16describe(waitForActionAsync, () => { 17 it(`wait for a given action to return a truthy value`, async () => { 18 const fn = jest.fn(() => 'd'); 19 const result = await waitForActionAsync({ 20 action: fn, 21 interval: 100, 22 maxWaitTime: 1000, 23 }); 24 expect(result).toEqual('d'); 25 expect(fn).toHaveBeenCalledTimes(1); 26 }); 27 it(`times out waiting for a given action to return a truthy value`, async () => { 28 const fn = jest.fn(() => ''); 29 const result = await waitForActionAsync({ 30 action: fn, 31 interval: 80, 32 maxWaitTime: 100, 33 }); 34 expect(result).toEqual(''); 35 expect(fn).toHaveBeenCalledTimes(2); 36 }, 500); 37}); 38 39describe(resolveWithTimeout, () => { 40 it(`times out`, async () => { 41 jest.useFakeTimers(); 42 // Create a function that never resolves. 43 const fn = jest.fn(() => new Promise(() => {})); 44 45 const promise = resolveWithTimeout(fn, { timeout: 50, errorMessage: 'Timeout' }); 46 jest.advanceTimersByTime(50); 47 await expect(promise).rejects.toThrowError('Timeout'); 48 49 // Ensure the function was called. 50 expect(fn).toBeCalled(); 51 }); 52 it(`resolves in time`, async () => { 53 jest.useFakeTimers(); 54 // Create a function that never resolves. 55 const fn = jest.fn(async () => 'foobar'); 56 57 const promise = resolveWithTimeout(fn, { timeout: 50 }); 58 jest.advanceTimersByTime(49); 59 await expect(promise).resolves.toEqual('foobar'); 60 // Ensure the function was called. 61 expect(fn).toBeCalled(); 62 }); 63}); 64