addons/isl-server/src/__tests__/utils.test.tsblame
View source
b69ab311/**
b69ab312 * Copyright (c) Meta Platforms, Inc. and affiliates.
b69ab313 *
b69ab314 * This source code is licensed under the MIT license found in the
b69ab315 * LICENSE file in the root directory of this source tree.
b69ab316 */
b69ab317
b69ab318import {serializeAsyncCall, sleep} from '../utils';
b69ab319
b69ab3110function flushPromises() {
b69ab3111 return new Promise(res => jest.requireActual('timers').setTimeout(res, 0));
b69ab3112}
b69ab3113
b69ab3114describe('serializeAsyncCall', () => {
b69ab3115 it('only runs one at a time', async () => {
b69ab3116 jest.useFakeTimers();
b69ab3117 const runTime = async (t: number) => {
b69ab3118 jest.advanceTimersByTime(t);
b69ab3119 await flushPromises();
b69ab3120 };
b69ab3121 let nextId = 0;
b69ab3122 const started: Array<number> = [];
b69ab3123 const finished: Array<number> = [];
b69ab3124 const testFn = serializeAsyncCall(async () => {
b69ab3125 const id = nextId++;
b69ab3126 started.push(id);
b69ab3127 await sleep(40);
b69ab3128 finished.push(id);
b69ab3129 });
b69ab3130
b69ab3131 testFn(); // This one is run immediately
b69ab3132 expect(started).toEqual([0]);
b69ab3133 expect(finished).toEqual([]); // not finished running
b69ab3134 await runTime(10);
b69ab3135 testFn(); // this one queues up while the first is still running
b69ab3136 expect(started).toEqual([0]); // 1 not running yet
b69ab3137 expect(finished).toEqual([]);
b69ab3138 await runTime(10);
b69ab3139 testFn(); // we already have an invocation queued,
b69ab3140 expect(started).toEqual([0]);
b69ab3141 expect(finished).toEqual([]);
b69ab3142
b69ab3143 await runTime(60);
b69ab3144 expect(started).toEqual([0, 1]);
b69ab3145 expect(finished).toEqual([0]);
b69ab3146
b69ab3147 await runTime(60);
b69ab3148 expect(started).toEqual([0, 1]);
b69ab3149 expect(finished).toEqual([0, 1]);
b69ab3150
b69ab3151 // nothing more to run
b69ab3152 await runTime(100);
b69ab3153 expect(started).toEqual([0, 1]);
b69ab3154 expect(finished).toEqual([0, 1]);
b69ab3155 });
b69ab3156
b69ab3157 it('returns the same result beyond being queued once', async () => {
b69ab3158 jest.useFakeTimers();
b69ab3159 let callNumber = 1;
b69ab3160 const testFn = serializeAsyncCall(() => {
b69ab3161 return Promise.resolve(callNumber++);
b69ab3162 });
b69ab3163
b69ab3164 const promise1 = testFn();
b69ab3165 const promise2 = testFn();
b69ab3166 const promise3 = testFn();
b69ab3167
b69ab3168 const values = await Promise.all([promise1, promise2, promise3]);
b69ab3169 expect(values).toEqual([1, 2, 2]);
b69ab3170 });
b69ab3171});