Created
July 21, 2024 07:03
-
-
Save McNull/9a52ade9d08acc29f11a9f423af83205 to your computer and use it in GitHub Desktop.
A no-bullshit-stupid-simple-test-runner for node
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
/* | |
// USAGE: | |
const { describe, it, run, assert } = require('./stupid-test-runner.js'); | |
describe('Philosophers and Their Unlikely Assertions', () => { | |
describe('Socrates', () => { | |
it('should know that he knows nothing', async () => { | |
const url = 'https://socratic.com/paradox/knowledge'; | |
const result = await fetch(url).then(x => x.text()); | |
assert(!result, 'Socrates claims to know something!'); | |
}); | |
}); | |
describe('Descartes', () => { | |
it('should think, therefore he is', () => { | |
const thinking = true; | |
assert(thinking === true, 'Descartes is not thinking?'); | |
}); | |
}); | |
}); | |
run(); | |
*/ | |
const A_DOUBLE_LINE = '========================================'; | |
const A_SINGLE_LINE = '----------------------------------------'; | |
const root = { | |
name: 'root', | |
tests: [], | |
children: [], | |
}; | |
const stack = [root]; | |
function create(name) { | |
return { | |
name, | |
tests: [], | |
children: [], | |
failures: 0, | |
}; | |
} | |
function push(context) { | |
stack[stack.length - 1].children.push(context); | |
stack.push(context); | |
} | |
function pop() { | |
stack.pop(); | |
} | |
function currentContext() { | |
return stack[stack.length - 1]; | |
} | |
async function runContext(context) { | |
let failures = 0; | |
console.log(A_DOUBLE_LINE); | |
console.log(`${context.name}`); | |
for (const test of context.tests) { | |
console.log(A_SINGLE_LINE); | |
console.log(`${test.name}`); | |
try { | |
await test.fn(); | |
} catch (error) { | |
console.error(error); | |
failures++; | |
} | |
} | |
for (const child of context.children) { | |
failures += await runContext(child); | |
} | |
context.failures = failures; | |
return failures; | |
} | |
async function describe(name, fn) { | |
const context = create(name); | |
push(context); | |
await fn(); | |
pop(); | |
} | |
async function it(name, fn) { | |
const context = currentContext(); | |
context.tests.push({ name, fn }); | |
} | |
async function run() { | |
let current = root; | |
await runContext(current); | |
console.log(); | |
console.log(A_SINGLE_LINE); | |
console.log(`Failures: ${current.failures}`); | |
console.log(A_SINGLE_LINE); | |
} | |
function assert(test, msg = 'Assertion failed') { | |
if (!test) { | |
throw new Error(msg); | |
} | |
} | |
module.exports = { | |
describe, | |
it, | |
run, | |
assert, | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment