forked from vitest-dev/vitest
/
context.ts
75 lines (63 loc) · 2.17 KB
/
context.ts
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
import type { Awaitable, RuntimeContext, SuiteCollector, Test, TestContext } from '../types'
import { createExpect } from '../integrations/chai'
import { clearTimeout, getWorkerState, setTimeout } from '../utils'
export const collectorContext: RuntimeContext = {
tasks: [],
currentSuite: null,
}
export function collectTask(task: SuiteCollector) {
collectorContext.currentSuite?.tasks.push(task)
}
export async function runWithSuite(suite: SuiteCollector, fn: (() => Awaitable<void>)) {
const prev = collectorContext.currentSuite
collectorContext.currentSuite = suite
await fn()
collectorContext.currentSuite = prev
}
export function getDefaultTestTimeout() {
return getWorkerState().config.testTimeout
}
export function getDefaultHookTimeout() {
return getWorkerState().config.hookTimeout
}
export function withTimeout<T extends((...args: any[]) => any)>(
fn: T,
timeout = getDefaultTestTimeout(),
isHook = false,
): T {
if (timeout <= 0 || timeout === Infinity)
return fn
return ((...args: (T extends ((...args: infer A) => any) ? A : never)) => {
return Promise.race([fn(...args), new Promise((resolve, reject) => {
const timer = setTimeout(() => {
clearTimeout(timer)
reject(new Error(makeTimeoutMsg(isHook, timeout)))
}, timeout)
// `unref` might not exist in browser
timer.unref?.()
})]) as Awaitable<void>
}) as T
}
export function createTestContext(test: Test): TestContext {
const context = function () {
throw new Error('done() callback is deprecated, use promise instead')
} as unknown as TestContext
context.meta = test
let _expect: Vi.ExpectStatic | undefined
Object.defineProperty(context, 'expect', {
get() {
if (!_expect)
_expect = createExpect(test)
return _expect
},
})
Object.defineProperty(context, '_local', {
get() {
return _expect != null
},
})
return context
}
function makeTimeoutMsg(isHook: boolean, timeout: number) {
return `${isHook ? 'Hook' : 'Test'} timed out in ${timeout}ms.\nIf this is a long-running test, pass a timeout value as the last argument or configure it globally with "${isHook ? 'hookTimeout' : 'testTimeout'}".`
}