Skip to content

Instantly share code, notes, and snippets.

@marianoguerra
Created August 19, 2025 08:22
Show Gist options
  • Save marianoguerra/c39763c3e4a5680314ad41987117879b to your computer and use it in GitHub Desktop.
Save marianoguerra/c39763c3e4a5680314ad41987117879b to your computer and use it in GitHub Desktop.
Mini Unit Test
export const test = (name, fn) => {
try {
console.group(name);
fn();
} catch (error) {
console.error(error);
} finally {
console.groupEnd();
}
};
export const isEq = (actual, expected, name = 'isEq') => {
if (actual !== expected) {
console.error(`❌: ${name}`, actual, expected);
throw new Error(`${name} failed`);
} else {
console.info('✅', name);
}
};
export const isOk = (value, name = 'isOk') => isEq(value, true, name);
export const isDeepEq = (actual, expected, name = 'isDeepEq') => {
if (!deepEquals(actual, expected)) {
console.error(`❌: ${name}`, actual, expected);
throw new Error(`Expected ${expected} but got ${actual}`);
} else {
console.info('✅', name);
}
};
// adapted from https://jsr.io/@ordo-pink/[email protected]
export const deepEquals = (x, y) => {
if (typeof x !== typeof y) return false;
if (Array.isArray(x))
return (
Array.isArray(y) &&
x.length === y.length &&
x.reduce(arrValueDeepEquals(y), true)
);
if (isObj(x)) {
if (!isObj(y)) return false;
const keysOfX = Object.keys(x);
return (
keysOfX.length === Object.keys(y).length &&
keysOfX.reduce(objValueDeepEquals(x, y), true)
);
}
return x === y;
};
const isObj = (x) => !!x && typeof x === 'object';
const arrValueDeepEquals = (y) => (acc, item, index) =>
acc && deepEquals(item, y[index]);
const objValueDeepEquals = (x, y) => (acc, key) =>
acc && deepEquals(x[key], y[key]);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment