metaltest/lib/metaltest.js

76 lines
1.7 KiB
JavaScript
Raw Normal View History

2022-12-05 17:07:06 -05:00
const metaltest = (title) => {
const suite = []
const only = []
const before = []
const after = []
2022-12-06 20:03:40 -05:00
const end = []
2022-12-05 17:07:06 -05:00
let success = 0
let fail = 0
const testSuccess = []
const testFail = []
const runner = (name, fn) => {
suite.push({ name, fn })
}
runner.only = (name, fn) => { only.push({ name, fn }) }
runner.before = (fn) => { before.push(fn) }
runner.after = (fn) => { after.push(fn) }
2022-12-06 20:03:40 -05:00
runner.end = (name, fn) => { end.push({ name, fn }) }
2022-12-05 17:07:06 -05:00
2022-12-05 22:38:52 -05:00
const notify = async (reporters, event, ...args) => {
for (const reporter of reporters) {
if (!reporter[event]) continue
2022-12-05 17:07:06 -05:00
2022-12-05 22:38:52 -05:00
await reporter[event](...args)
}
}
runner.run = async (...reporters) => {
notify(reporters, 'start', title)
2022-12-05 17:07:06 -05:00
const tests = only.length ? only : suite
for (const test of tests) {
try {
for (const fn of before) await fn()
await test.fn()
2022-12-06 12:55:41 -05:00
2022-12-05 17:07:06 -05:00
success++
2022-12-06 12:55:41 -05:00
testSuccess.push(test)
2022-12-05 22:38:52 -05:00
notify(reporters, 'success', test)
2022-12-05 17:07:06 -05:00
}
2022-12-05 22:41:37 -05:00
catch (error) {
2022-12-05 17:07:06 -05:00
fail++
2022-12-05 22:41:37 -05:00
testFail.push(Object.assign({}, test, { error }))
notify(reporters, 'fail', test, error)
2022-12-05 17:07:06 -05:00
}
}
2022-12-06 20:03:40 -05:00
const stats = { title, success, fail, total: success + fail, testSuccess, testFail }
for (const test of end) {
try {
await test.fn(stats)
success++
testSuccess.push(test)
notify(reporters, 'success', test)
} catch (error) {
fail++
testFail.push(Object.assign({}, test, { error }))
notify(reporters, 'fail', test, error)
}
}
2022-12-05 17:07:06 -05:00
for (const fn of after) await fn()
2022-12-05 22:38:52 -05:00
notify(reporters, 'end', stats)
2022-12-05 17:07:06 -05:00
return stats
}
return runner
}
export { metaltest }