From a608ff4af825fb749a6ac3d77d6f5a3bc7b1820f Mon Sep 17 00:00:00 2001 From: Liam Date: Sun, 17 Mar 2024 16:12:50 -0400 Subject: [PATCH] Add assertion utilities --- assets/js/utils/__tests__/assert.spec.ts | 35 ++++++++++++++++++++++++ assets/js/utils/assert.ts | 28 +++++++++++++++++++ 2 files changed, 63 insertions(+) create mode 100644 assets/js/utils/__tests__/assert.spec.ts create mode 100644 assets/js/utils/assert.ts diff --git a/assets/js/utils/__tests__/assert.spec.ts b/assets/js/utils/__tests__/assert.spec.ts new file mode 100644 index 00000000..a0415168 --- /dev/null +++ b/assets/js/utils/__tests__/assert.spec.ts @@ -0,0 +1,35 @@ +import { assertNotNull, assertNotUndefined, assertType } from '../assert'; + +describe('Assertion utilities', () => { + describe('assertNotNull', () => { + it('should return non-null values', () => { + expect(assertNotNull(1)).toEqual(1); + expect(assertNotNull('anything')).toEqual('anything'); + }); + + it('should throw when passed a null value', () => { + expect(() => assertNotNull(null)).toThrow('Expected non-null value'); + }); + }); + + describe('assertNotUndefined', () => { + it('should return non-undefined values', () => { + expect(assertNotUndefined(1)).toEqual(1); + expect(assertNotUndefined('anything')).toEqual('anything'); + }); + + it('should throw when passed an undefined value', () => { + expect(() => assertNotUndefined(undefined)).toThrow('Expected non-undefined value'); + }); + }); + + describe('assertType', () => { + it('should return values of the generic type', () => { + expect(assertType({}, Object)).toEqual({}); + }); + + it('should throw when passed a value of the wrong type', () => { + expect(() => assertType('anything', Number)).toThrow('Expected value of type'); + }); + }); +}); diff --git a/assets/js/utils/assert.ts b/assets/js/utils/assert.ts new file mode 100644 index 00000000..09a17433 --- /dev/null +++ b/assets/js/utils/assert.ts @@ -0,0 +1,28 @@ +export function assertNotNull(value: T | null): T { + if (value === null) { + throw new Error('Expected non-null value'); + } + + return value; +} + +export function assertNotUndefined(value: T | undefined): T { + // eslint-disable-next-line no-undefined + if (value === undefined) { + throw new Error('Expected non-undefined value'); + } + + return value; +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +type Constructor = { new (...args: any[]): T }; + +export function assertType(value: any, c: Constructor): T { + if (value instanceof c) { + return value; + } + + throw new Error('Expected value of type'); +} +/* eslint-enable @typescript-eslint/no-explicit-any */