Skip to content

Instantly share code, notes, and snippets.

@kigiri
Last active March 11, 2020 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kigiri/290039051d500e33bb2af76cced3f4c7 to your computer and use it in GitHub Desktop.
Save kigiri/290039051d500e33bb2af76cced3f4c7 to your computer and use it in GitHub Desktop.
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