metaltest/lib/metaltest.js

60 lines
1.3 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 = []
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-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)
notify(reporters, 'before')
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()
success++
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:38:52 -05:00
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
}
}
for (const fn of after) await fn()
2022-12-05 22:38:52 -05:00
notify(reporters, 'after')
2022-12-05 17:07:06 -05:00
const stats = { title, success, fail, total: success + fail, testSuccess, testFail }
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 }