Created
August 19, 2025 08:22
-
-
Save marianoguerra/c39763c3e4a5680314ad41987117879b to your computer and use it in GitHub Desktop.
Mini Unit Test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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