Last active
March 11, 2020 19:22
-
-
Save kigiri/290039051d500e33bb2af76cced3f4c7 to your computer and use it in GitHub Desktop.
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
const eq = (a, b) => { | |
if (a === b) return true | |
if (!a || !b) return false | |
if (typeof a !== typeof b) return false | |
if (typeof a === 'number' && Number.isNaN(a) && Number.isNaN(b)) return true | |
if (typeof a === 'object') { | |
if (a.constructor !== b.constructor) return false | |
const entries = Object.entries(a) | |
if (entries.length !== Object.values(b).length) return false | |
for (const [k,v] of entries) { | |
if (!eq(b[k], v)) return false | |
} | |
return true | |
} | |
throw err | |
} | |
const tests = [] | |
const tester = f => ({ description, test, expect }) => { | |
const count = tests.length + 1 | |
tests.push(async ctx => { | |
try { | |
const got = await f(test)(ctx) | |
if (!eq(got, expect)) { | |
console.log({ got, expect }) | |
throw Error('Unexpected test result') | |
} | |
console.log(`PASS #${count} ${description}`) | |
} catch (err) { | |
console.log(`FAIL #${count} ${description}`) | |
const left = tests.length - count | |
left && console.log(`...and ${left} ${left > 1 ? 'tests lefts' : 'test left'}`) | |
console.log(err.message) | |
throw err | |
} | |
return ctx | |
}) | |
} | |
export const ok = tester(test => test) | |
export const fail = tester(test => async args => { | |
try { | |
const err = Error('Should have failed') | |
err.result = await test(args) | |
return Promise.reject(err) | |
} catch ({ message, trace, ...rest }) { | |
return { message, ...rest } | |
} | |
}) | |
setTimeout((setup = () => {}) => | |
tests.reduce((q, test) => q.then(test), Promise.resolve(setup())) | |
.catch(_ => _)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment