Last active
May 6, 2024 04:59
-
-
Save treshugart/b159a794b8b6d58ce2f3f353e24ba1e9 to your computer and use it in GitHub Desktop.
Promised-based testing using console / error / info in ~60 LoC complete with suites, custom reporters, summaries and a few assertions via Error.
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 done = () => {} | |
const indent = (depth, info) => [...Array(depth)].reduce(p => `${p} `, '') + info; | |
const reporter = { | |
fail: ({ depth, message, name }) => { | |
console.info(indent(depth, `✗ ${name}`)); | |
console.error(indent(depth + 1, message)); | |
}, | |
pass: ({ depth, name }) => console.info(indent(depth, `✓ ${name}`)), | |
suite: ({ depth, name }) => console.info(indent(depth, name)), | |
test: () => {} | |
}; | |
let deferred = Promise.resolve(); | |
let depth = 0; | |
function test (name, func, opts = { done, reporter }) { | |
const tests = []; | |
deferred | |
.then(() => reporter.suite({ depth, name })) | |
.then(() => ++depth); | |
func(function (name, ...results) { | |
deferred | |
.then(() => tests.push({ errors, depth, names: suites.concat(name) })); | |
deferred = results.reduce((a, b) => a | |
.then(() => reporter.test({ depth, name })) | |
.catch(e => { | |
tests[tests.length - 1].errors.push(e.message); | |
reporter.fail({ depth, message: e.message, name }); | |
}) | |
.then(b) | |
.then(r => reporter.pass({ depth, name })), deferred); | |
deferred | |
.then(() => --depth); | |
}); | |
deferred | |
.then(() => done(tests)); | |
} | |
function str (v) { | |
return JSON.stringify(v); | |
} | |
function toss (msg, info) { | |
throw new Error(`${msg}${info ? `: ${info}` : ''}`); | |
} | |
function assert(v, info) { | |
if (!v) { | |
toss('assertion failed', info); | |
} | |
} | |
function eq (v1, v2, info) { | |
if (v1 !== v2) { | |
toss(`expected ${str(v1)} to *not* equal ${str(v2)}`, info); | |
} | |
} | |
function ne (v1, v2, info) { | |
if (v1 === v2) { | |
toss(`expected ${str(v1)} to *not* equal ${str(v2)}`, info); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment