forked from vitest-dev/vitest
-
Notifications
You must be signed in to change notification settings - Fork 0
/
context.ts
57 lines (47 loc) · 1.66 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
import type { Awaitable, DoneCallback, RuntimeContext, SuiteCollector, TestFunction } from '../types'
export const context: RuntimeContext = {
tasks: [],
currentSuite: null,
}
export function collectTask(task: SuiteCollector) {
context.currentSuite?.tasks.push(task)
}
export async function runWithSuite(suite: SuiteCollector, fn: (() => Awaitable<void>)) {
const prev = context.currentSuite
context.currentSuite = suite
await fn()
context.currentSuite = prev
}
export function getDefaultTestTimeout() {
return __vitest_worker__!.config!.testTimeout
}
export function getDefaultHookTimeout() {
return __vitest_worker__!.config!.hookTimeout
}
export function withTimeout<T extends((...args: any[]) => any)>(fn: T, _timeout?: number): T {
const timeout = _timeout ?? getDefaultTestTimeout()
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(`Test timed out in ${timeout}ms.`))
}, timeout)
timer.unref()
})]) as Awaitable<void>
}) as T
}
function ensureAsyncTest(fn: TestFunction): () => Awaitable<void> {
if (!fn.length)
return fn as () => Awaitable<void>
return () => new Promise((resolve, reject) => {
const done: DoneCallback = (...args: any[]) => args[0] // reject on truthy values
? reject(args[0])
: resolve()
fn(done)
})
}
export function normalizeTest(fn: TestFunction, timeout?: number): () => Awaitable<void> {
return withTimeout(ensureAsyncTest(fn), timeout)
}