-
Notifications
You must be signed in to change notification settings - Fork 296
/
Copy pathtest.js
88 lines (73 loc) · 2.29 KB
/
test.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
import process from 'node:process'
/* eslint no-console: 0 */
import util from 'node:util'
let done = 0
let only = false
let ignored = 0
let failed = false
let promise = Promise.resolve()
const tests = {}
, ignore = {}
export const nt = () => ignored++
export const ot = (...rest) => (only = true, test(true, ...rest))
export const t = (...rest) => test(false, ...rest)
t.timeout = 5
async function test(o, name, options, fn) {
typeof options !== 'object' && (fn = options, options = {})
const line = new Error().stack.split('\n')[3].match(':([0-9]+):')[1]
await 1
if (only && !o)
return
tests[line] = { fn, line, name }
promise = promise.then(() => Promise.race([
new Promise((resolve, reject) =>
fn.timer = setTimeout(() => reject('Timed out'), (options.timeout || t.timeout) * 1000)
),
failed
? (ignored++, ignore)
: fn()
]))
.then(async x => {
clearTimeout(fn.timer)
if (x === ignore)
return
if (!Array.isArray(x))
throw new Error('Test should return result array')
const [expected, got] = await Promise.all(x)
if (expected !== got) {
failed = true
throw new Error(util.inspect(expected) + ' != ' + util.inspect(got))
}
tests[line].succeeded = true
process.stdout.write('✅')
})
.catch(err => {
tests[line].failed = failed = true
tests[line].error = err instanceof Error ? err : new Error(util.inspect(err))
})
.then(() => {
++done === Object.keys(tests).length && exit()
})
}
function exit() {
let success = true
Object.values(tests).every((x) => {
if (x.succeeded)
return true
success = false
x.cleanup
? console.error('⛔️', x.name + ' at line', x.line, 'cleanup failed', '\n', util.inspect(x.cleanup))
: console.error('⛔️', x.name + ' at line', x.line, x.failed
? 'failed'
: 'never finished', x.error ? '\n' + util.inspect(x.error) : ''
)
})
only
? console.error('⚠️', 'Not all tests were run')
: ignored
? console.error('⚠️', ignored, 'ignored test' + (ignored === 1 ? '' : 's', '\n'))
: success
? console.log('🎉')
: console.error('⚠️', 'Not good')
!process.exitCode && (!success || only || ignored) && (process.exitCode = 1)
}