| 1 | /** |
| 2 | * Copyright (c) Meta Platforms, Inc. and affiliates. |
| 3 | * |
| 4 | * This source code is licensed under the MIT license found in the |
| 5 | * LICENSE file in the root directory of this source tree. |
| 6 | */ |
| 7 | |
| 8 | import {serializeAsyncCall, sleep} from '../utils'; |
| 9 | |
| 10 | function flushPromises() { |
| 11 | return new Promise(res => jest.requireActual('timers').setTimeout(res, 0)); |
| 12 | } |
| 13 | |
| 14 | describe('serializeAsyncCall', () => { |
| 15 | it('only runs one at a time', async () => { |
| 16 | jest.useFakeTimers(); |
| 17 | const runTime = async (t: number) => { |
| 18 | jest.advanceTimersByTime(t); |
| 19 | await flushPromises(); |
| 20 | }; |
| 21 | let nextId = 0; |
| 22 | const started: Array<number> = []; |
| 23 | const finished: Array<number> = []; |
| 24 | const testFn = serializeAsyncCall(async () => { |
| 25 | const id = nextId++; |
| 26 | started.push(id); |
| 27 | await sleep(40); |
| 28 | finished.push(id); |
| 29 | }); |
| 30 | |
| 31 | testFn(); // This one is run immediately |
| 32 | expect(started).toEqual([0]); |
| 33 | expect(finished).toEqual([]); // not finished running |
| 34 | await runTime(10); |
| 35 | testFn(); // this one queues up while the first is still running |
| 36 | expect(started).toEqual([0]); // 1 not running yet |
| 37 | expect(finished).toEqual([]); |
| 38 | await runTime(10); |
| 39 | testFn(); // we already have an invocation queued, |
| 40 | expect(started).toEqual([0]); |
| 41 | expect(finished).toEqual([]); |
| 42 | |
| 43 | await runTime(60); |
| 44 | expect(started).toEqual([0, 1]); |
| 45 | expect(finished).toEqual([0]); |
| 46 | |
| 47 | await runTime(60); |
| 48 | expect(started).toEqual([0, 1]); |
| 49 | expect(finished).toEqual([0, 1]); |
| 50 | |
| 51 | // nothing more to run |
| 52 | await runTime(100); |
| 53 | expect(started).toEqual([0, 1]); |
| 54 | expect(finished).toEqual([0, 1]); |
| 55 | }); |
| 56 | |
| 57 | it('returns the same result beyond being queued once', async () => { |
| 58 | jest.useFakeTimers(); |
| 59 | let callNumber = 1; |
| 60 | const testFn = serializeAsyncCall(() => { |
| 61 | return Promise.resolve(callNumber++); |
| 62 | }); |
| 63 | |
| 64 | const promise1 = testFn(); |
| 65 | const promise2 = testFn(); |
| 66 | const promise3 = testFn(); |
| 67 | |
| 68 | const values = await Promise.all([promise1, promise2, promise3]); |
| 69 | expect(values).toEqual([1, 2, 2]); |
| 70 | }); |
| 71 | }); |
| 72 | |