Skip to content

Instantly share code, notes, and snippets.

@treshugart
Last active January 14, 2017 13:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save treshugart/b159a794b8b6d58ce2f3f353e24ba1e9 to your computer and use it in GitHub Desktop.
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.
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