Skip to content

Commit

Permalink
refactor(core): add isPromise
Browse files Browse the repository at this point in the history
  • Loading branch information
notaphplover committed Nov 30, 2024
1 parent e846667 commit d9ab894
Show file tree
Hide file tree
Showing 2 changed files with 65 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
import { beforeAll, describe, expect, it } from '@jest/globals';

import { isPromise } from './isPromise';

describe(isPromise.name, () => {
describe.each<[string, unknown, boolean]>([
['null', null, false],
['a string', 'string-fixture', false],
['a function with no "then" property', () => undefined, false],
['an object with no "then" property', {}, false],
[
'a function with non function "then" property',
(() => {
const value: (() => void) & {
then?: unknown;
} = () => undefined;

value.then = 'fixture';

return value;
})(),
false,
],
['an object with non function "then" property', { then: 'fixture' }, false],
[
'a function with function "then" property',
(() => {
const value: (() => void) & {
then?: unknown;
} = () => undefined;

value.then = () => undefined;

return value;
})(),
true,
],
[
'an object with function "then" property',
{ then: () => undefined },
true,
],
])('having %s', (_: string, value: unknown, expectedResult: boolean) => {
describe('when called', () => {
let result: unknown;

beforeAll(() => {
result = isPromise(value);
});

it('should return expected value', () => {
expect(result).toBe(expectedResult);
});
});
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
export function isPromise<T>(object: unknown): object is Promise<T> {
const isObjectOrFunction: boolean =
(typeof object === 'object' && object !== null) ||
typeof object === 'function';

return (
isObjectOrFunction && typeof (object as PromiseLike<T>).then === 'function'
);
}

0 comments on commit d9ab894

Please sign in to comment.