-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
context.ts
65 lines (54 loc) · 1.98 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
import type { Awaitable, DoneCallback, RuntimeContext, SuiteCollector, TestFunction } from '../types'
import { clearTimeout, getWorkerState, setTimeout } from '../utils'
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 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)
timer.unref()
})]) as Awaitable<void>
}) as T
}
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'}".`
}
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)
}