Skip to content

Commit

Permalink
Add assertion utilities
Browse files Browse the repository at this point in the history
  • Loading branch information
liamwhite committed Mar 17, 2024
1 parent 3cc9e90 commit a608ff4
Show file tree
Hide file tree
Showing 2 changed files with 63 additions and 0 deletions.
35 changes: 35 additions & 0 deletions assets/js/utils/__tests__/assert.spec.ts
Original file line number Diff line number Diff line change
@@ -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');
});
});
});
28 changes: 28 additions & 0 deletions assets/js/utils/assert.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
export function assertNotNull<T>(value: T | null): T {
if (value === null) {
throw new Error('Expected non-null value');
}

return value;
}

export function assertNotUndefined<T>(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<T> = { new (...args: any[]): T };

export function assertType<T>(value: any, c: Constructor<T>): T {
if (value instanceof c) {
return value;
}

throw new Error('Expected value of type');
}
/* eslint-enable @typescript-eslint/no-explicit-any */

0 comments on commit a608ff4

Please sign in to comment.