diff --git a/desktop/flipper-common/src/__tests__/timeout.node.tsx b/desktop/flipper-common/src/__tests__/timeout.node.tsx new file mode 100644 index 000000000..4cb8ad563 --- /dev/null +++ b/desktop/flipper-common/src/__tests__/timeout.node.tsx @@ -0,0 +1,34 @@ +/** + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + * + * @format + */ + +import {timeout} from '../utils/timeout'; + +test('resolves', async () => { + const p = Promise.resolve(3); + + await expect(timeout(100, p)).resolves.toBe(3); +}); + +test('rejects', async () => { + const p = Promise.reject(new Error('oops')); + + await expect(timeout(100, p)).rejects.toMatchInlineSnapshot(`[Error: oops]`); +}); + +test('times out', async () => { + let lateResolve: any; + const p = new Promise((r) => { + lateResolve = r; + }); + + await expect(timeout(100, p)).rejects.toMatchInlineSnapshot( + `[Error: Timed out in 100 ms.]`, + ); + lateResolve(); // avoid dangling promise after test +}); diff --git a/desktop/flipper-common/src/utils/timeout.tsx b/desktop/flipper-common/src/utils/timeout.tsx index 743b7a362..077d0a529 100644 --- a/desktop/flipper-common/src/utils/timeout.tsx +++ b/desktop/flipper-common/src/utils/timeout.tsx @@ -7,18 +7,21 @@ * @format */ -import {sleep} from './sleep'; - export function timeout( ms: number, promise: Promise, timeoutMessage?: string, ): Promise { - // Create a promise that rejects in milliseconds - const timeout = sleep(ms).then(() => { - throw new Error(timeoutMessage || `Timed out in ${ms} ms.`); - }); + return new Promise((resolve, reject) => { + const timeoutHandle = setTimeout(() => { + reject(new Error(timeoutMessage || `Timed out in ${ms} ms.`)); + }, ms); - // Returns a race between our timeout and the passed in promise - return Promise.race([promise, timeout]); + promise + .then(resolve) + .finally(() => { + clearTimeout(timeoutHandle); + }) + .catch(reject); + }); } diff --git a/desktop/flipper-ui-core/src/utils/__tests__/promiseTimeout.node.tsx b/desktop/flipper-ui-core/src/utils/__tests__/promiseTimeout.node.tsx index 92bdc8ba5..91f02b2e8 100644 --- a/desktop/flipper-ui-core/src/utils/__tests__/promiseTimeout.node.tsx +++ b/desktop/flipper-ui-core/src/utils/__tests__/promiseTimeout.node.tsx @@ -9,7 +9,7 @@ import promiseTimeout from '../promiseTimeout'; -test('test promiseTimeout for timeout to happen', () => { +test('test promiseTimeout for timeout to happen', async () => { const promise = promiseTimeout( 200, new Promise((resolve) => { @@ -17,11 +17,10 @@ test('test promiseTimeout for timeout to happen', () => { clearTimeout(id); resolve(); }, 500); - return 'Executed'; }), 'Timed out', ); - return expect(promise).rejects.toThrow('Timed out'); + await expect(promise).rejects.toThrow('Timed out'); }); test('test promiseTimeout for timeout not to happen', () => {