UNPKG

@applicvision/js-toolbox

Version:

A collection of tools for modern JavaScript development

77 lines (65 loc) 2.26 kB
export default function assert(value) { if (!value) { throw new AssertionError({ message: `${value} == true` }) } } assert.equal = (actual, expected, message) => { if (actual !== expected) { throw new AssertionError({ message: message ?? `Expected values to be strictly equal. ${actual} !== ${expected}` }) } } assert.doesNotThrow = (func) => { try { func() } catch (err) { throw new AssertionError({ message: 'Expected func not to throw' }) } } assert.notEqual = (actual, expected) => { if (actual === expected) { throw new AssertionError({ message: 'Expected "actual" to be strictly unequal to "expected"' }) } } assert.deepEqual = (actual, expected, keypath = []) => { if (Object.is(actual, expected)) { return } const actualTypeTag = Object.prototype.toString.call(actual) const expectedTypeTag = Object.prototype.toString.call(expected) if (actualTypeTag !== expectedTypeTag) { throw new AssertionError({ message: `Expected type ${expectedTypeTag}, but got ${actualTypeTag} at keypath ${keypath}` }) } const actualProto = Object.getPrototypeOf(actual) const expectedProto = Object.getPrototypeOf(expected) if (actualProto !== expectedProto) { throw new AssertionError({ message: `Expected prototype ${expectedProto.constructor.name}, but got ${actual.constructor.name} at keypath ${keypath}` }) } if (expected instanceof Set) { compareSets(actual, expected) } else if (expected instanceof Map) { // compareMaps(actual, expected) } else if (expected instanceof Object && !(expected instanceof Function)) { const actualKeys = Object.keys(actual) const expectedKeys = Object.keys(expected) const allKeys = [...new Set([...actualKeys, ...expectedKeys])] allKeys.forEach(key => { assert.deepEqual(actual[key], expected[key], keypath.concat(key)) }) } else { throw new AssertionError({ message: `Expected ${actual} to be ${expected}, at keypath: ${keypath}` }) } } function compareSets(actual, expected) { if (actual.size !== expected.size) { throw new AssertionError({ message: `Expected set of size ${expected.si}` }) } } export class AssertionError extends Error { constructor(options) { super(options.message) Error.captureStackTrace?.(this, options.stackStartFn) } }