metaltest/lib/metaltest.js

84 lines
1.8 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 = []
2022-12-06 20:18:42 -05:00
const stats = (type, test, error) => {
switch (type) {
case 'success':
success++
testSuccess.push(test)
break
case 'fail':
fail++
testFail.push(Object.assign({}, test, { error }))
break
}
2022-12-06 20:05:29 -05:00
return { title, success, fail, total: success + fail, testSuccess, testFail }
}
2022-12-05 17:07:06 -05:00
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 20:18:42 -05:00
stats('success', 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-06 20:18:42 -05:00
stats('fail', test, error)
2022-12-05 22:41:37 -05:00
notify(reporters, 'fail', test, error)
2022-12-05 17:07:06 -05:00
}
}
2022-12-06 20:03:40 -05:00
for (const test of end) {
try {
2022-12-06 20:05:29 -05:00
await test.fn(stats())
2022-12-06 20:03:40 -05:00
2022-12-06 20:18:42 -05:00
stats('success', test)
2022-12-06 20:03:40 -05:00
notify(reporters, 'success', test)
} catch (error) {
2022-12-06 20:18:42 -05:00
stats('fail', test, error)
2022-12-06 20:03:40 -05:00
notify(reporters, 'fail', test, error)
}
}
2022-12-05 17:07:06 -05:00
for (const fn of after) await fn()
2022-12-06 20:18:42 -05:00
const r = stats()
notify(reporters, 'end', r)
return r
2022-12-05 17:07:06 -05:00
}
return runner
}
export { metaltest }