/
setup.ts
76 lines (69 loc) · 1.75 KB
/
setup.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
76
import { Console } from 'console'
import { Writable } from 'stream'
import { environments } from '../integrations/env'
import { setupChai } from '../integrations/chai/setup'
import type { ResolvedConfig } from '../types'
import { toArray } from '../utils'
import { rpc } from './rpc'
let globalSetup = false
export async function setupGlobalEnv(config: ResolvedConfig) {
if (globalSetup)
return
globalSetup = true
setupConsoleLogSpy()
await setupChai()
if (config.globals)
(await import('../integrations/globals')).registerApiGlobally()
}
export function setupConsoleLogSpy() {
const stdout = new Writable({
write(data, encoding, callback) {
rpc().onUserConsoleLog({
type: 'stdout',
content: String(data),
taskId: __vitest_worker__.current?.id,
time: Date.now(),
})
callback()
},
})
const stderr = new Writable({
write(data, encoding, callback) {
rpc().onUserConsoleLog({
type: 'stderr',
content: String(data),
taskId: __vitest_worker__.current?.id,
time: Date.now(),
})
callback()
},
})
globalThis.console = new Console({
stdout,
stderr,
colorMode: true,
groupIndentation: 2,
})
}
export async function withEnv(
name: ResolvedConfig['environment'],
options: ResolvedConfig['environmentOptions'],
fn: () => Promise<void>,
) {
const env = await environments[name].setup(globalThis, options)
try {
await fn()
}
finally {
await env.teardown(globalThis)
}
}
export async function runSetupFiles(config: ResolvedConfig) {
const files = toArray(config.setupFiles)
await Promise.all(
files.map(async(file) => {
__vitest_worker__.moduleCache.delete(file)
await import(file)
}),
)
}