/
index.ts
189 lines (157 loc) · 4.78 KB
/
index.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
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
import { Console } from 'node:console'
import { Writable } from 'node:stream'
import { type UserConfig, type VitestRunMode, afterEach } from 'vitest'
import type { Vitest } from 'vitest/node'
import { startVitest } from 'vitest/node'
import { type Options, execa } from 'execa'
import stripAnsi from 'strip-ansi'
export async function runVitest(config: UserConfig, cliFilters: string[] = [], mode: VitestRunMode = 'test') {
// Reset possible previous runs
process.exitCode = 0
// Prevent possible process.exit() calls, e.g. from --browser
const exit = process.exit
process.exit = (() => { }) as never
const { getLogs, restore } = captureLogs()
let vitest: Vitest | undefined
try {
vitest = await startVitest(mode, cliFilters, {
watch: false,
reporters: ['verbose'],
...config,
})
}
catch (e: any) {
return {
stderr: `${getLogs().stderr}\n${e.message}`,
stdout: getLogs().stdout,
exitCode: process.exitCode,
vitest,
}
}
finally {
restore()
}
const exitCode = process.exitCode
process.exitCode = 0
process.exit = exit
return { ...getLogs(), exitCode, vitest }
}
function captureLogs() {
const stdout: string[] = []
const stderr: string[] = []
const streams = {
stdout: new Writable({
write(chunk, _, callback) {
stdout.push(chunk.toString())
callback()
},
}),
stderr: new Writable({
write(chunk, _, callback) {
stderr.push(chunk.toString())
callback()
},
}),
}
const originalConsole = globalThis.console
globalThis.console = new Console(streams)
const originalStdoutWrite = process.stdout.write
process.stdout.write = streams.stdout.write.bind(streams.stdout) as any
const originalStderrWrite = process.stderr.write
process.stderr.write = streams.stderr.write.bind(streams.stderr) as any
return {
restore: () => {
globalThis.console = originalConsole
process.stdout.write = originalStdoutWrite
process.stderr.write = originalStderrWrite
},
getLogs() {
return {
stdout: stripAnsi(stdout.join('')),
stderr: stripAnsi(stderr.join('')),
}
},
}
}
export async function runVitestCli(_options?: Options | string, ...args: string[]) {
let options = _options
if (typeof _options === 'string') {
args.unshift(_options)
options = undefined
}
const subprocess = execa('vitest', args, options as Options)
let setDone: (value?: unknown) => void
const isDone = new Promise(resolve => (setDone = resolve))
const vitest = {
stdout: '',
stderr: '',
stdoutListeners: [] as (() => void)[],
stderrListeners: [] as (() => void)[],
isDone,
write(text: string) {
this.resetOutput()
subprocess.stdin!.write(text)
},
waitForStdout(expected: string) {
return new Promise<void>((resolve, reject) => {
if (this.stdout.includes(expected))
return resolve()
const timeout = setTimeout(() => {
reject(new Error(`Timeout when waiting for output "${expected}".\nReceived:\n${this.stdout}. \nStderr:\n${this.stderr}`))
}, process.env.CI ? 20_000 : 4_000)
const listener = () => {
if (this.stdout.includes(expected)) {
if (timeout)
clearTimeout(timeout)
resolve()
}
}
this.stdoutListeners.push(listener)
})
},
waitForStderr(expected: string) {
return new Promise<void>((resolve, reject) => {
if (this.stderr.includes(expected))
return resolve()
const timeout = setTimeout(() => {
reject(new Error(`Timeout when waiting for error "${expected}".\nReceived:\n${this.stderr}`))
}, process.env.CI ? 20_000 : 4_000)
const listener = () => {
if (this.stderr.includes(expected)) {
if (timeout)
clearTimeout(timeout)
resolve()
}
}
this.stderrListeners.push(listener)
})
},
resetOutput() {
this.stdout = ''
this.stderr = ''
},
}
subprocess.stdout!.on('data', (data) => {
vitest.stdout += stripAnsi(data.toString())
vitest.stdoutListeners.forEach(fn => fn())
})
subprocess.stderr!.on('data', (data) => {
vitest.stderr += stripAnsi(data.toString())
vitest.stderrListeners.forEach(fn => fn())
})
subprocess.on('exit', () => setDone())
// Manually stop the processes so that each test don't have to do this themselves
afterEach(async () => {
if (subprocess.exitCode === null)
subprocess.kill()
await vitest.isDone
})
if (args.includes('--watch')) { // Wait for initial test run to complete
await vitest.waitForStdout('Waiting for file changes')
vitest.resetOutput()
}
else {
await vitest.isDone
}
return vitest
}