-
-
Notifications
You must be signed in to change notification settings - Fork 6.4k
/
Copy pathjestPerTestSetup.ts
287 lines (256 loc) · 7.98 KB
/
jestPerTestSetup.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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import fs from 'fs-extra'
import * as http from 'http'
import { resolve, dirname } from 'path'
import sirv from 'sirv'
import type {
ViteDevServer,
InlineConfig,
PluginOption,
ResolvedConfig,
Logger
} from 'vite'
import { createServer, build, mergeConfig } from 'vite'
import type { Page, ConsoleMessage } from 'playwright-chromium'
import type { RollupError, RollupWatcher, RollupWatcherEvent } from 'rollup'
const isBuildTest = !!process.env.VITE_TEST_BUILD
export function slash(p: string): string {
return p.replace(/\\/g, '/')
}
// injected by the test env
declare global {
const page: Page | undefined
const browserLogs: string[]
const serverLogs: string[]
const viteTestUrl: string | undefined
const watcher: RollupWatcher | undefined
let beforeAllError: Error | null // error caught in beforeAll, useful if you want to test error scenarios on build
}
declare const global: {
page?: Page
browserLogs: string[]
serverLogs: string[]
viteTestUrl?: string
watcher?: RollupWatcher
beforeAllError: Error | null
}
let server: ViteDevServer | http.Server
let tempDir: string
let rootDir: string
const setBeforeAllError = (err: Error | null) => {
global.beforeAllError = err
}
const getBeforeAllError = () => global.beforeAllError
//init with null so old errors don't carry over
setBeforeAllError(null)
const logs: string[] = (global.browserLogs = [])
const onConsole = (msg: ConsoleMessage) => {
logs.push(msg.text())
}
beforeAll(async () => {
const page = global.page
if (!page) {
return
}
try {
page.on('console', onConsole)
const testPath = expect.getState().testPath
const testName = slash(testPath).match(/playground\/([\w-]+)\//)?.[1]
// if this is a test placed under playground/xxx/__tests__
// start a vite server in that directory.
if (testName) {
const playgroundRoot = resolve(__dirname, '../packages/playground')
tempDir = resolve(__dirname, '../packages/temp/', testName)
// when `root` dir is present, use it as vite's root
const testCustomRoot = resolve(tempDir, 'root')
rootDir = fs.existsSync(testCustomRoot) ? testCustomRoot : tempDir
const testCustomServe = resolve(dirname(testPath), 'serve.js')
if (fs.existsSync(testCustomServe)) {
// test has custom server configuration.
const { serve, preServe } = require(testCustomServe)
if (preServe) {
await preServe(rootDir, isBuildTest)
}
if (serve) {
server = await serve(rootDir, isBuildTest)
return
}
}
const testCustomConfig = resolve(dirname(testPath), 'vite.config.js')
let config: InlineConfig | undefined
if (fs.existsSync(testCustomConfig)) {
// test has custom server configuration.
config = require(testCustomConfig)
}
const serverLogs: string[] = []
const options: InlineConfig = {
root: rootDir,
logLevel: 'silent',
server: {
watch: {
// During tests we edit the files too fast and sometimes chokidar
// misses change events, so enforce polling for consistency
usePolling: true,
interval: 100
},
host: true,
fs: {
strict: !isBuildTest
}
},
build: {
// skip transpilation during tests to make it faster
target: 'esnext'
},
customLogger: createInMemoryLogger(serverLogs)
}
setupConsoleWarnCollector(serverLogs)
global.serverLogs = serverLogs
if (!isBuildTest) {
process.env.VITE_INLINE = 'inline-serve'
server = await (
await createServer(mergeConfig(options, config || {}))
).listen()
// use resolved port/base from server
const base = server.config.base === '/' ? '' : server.config.base
const url =
(global.viteTestUrl = `http://localhost:${server.config.server.port}${base}`)
await page.goto(url)
} else {
process.env.VITE_INLINE = 'inline-build'
// determine build watch
let resolvedConfig: ResolvedConfig
const resolvedPlugin: () => PluginOption = () => ({
name: 'vite-plugin-watcher',
configResolved(config) {
resolvedConfig = config
}
})
options.plugins = [resolvedPlugin()]
const rollupOutput = await build(mergeConfig(options, config || {}))
const isWatch = !!resolvedConfig!.build.watch
// in build watch,call startStaticServer after the build is complete
if (isWatch) {
global.watcher = rollupOutput as RollupWatcher
await notifyRebuildComplete(global.watcher)
}
const url = (global.viteTestUrl = await startStaticServer(config))
await page.goto(url)
}
}
} catch (e: any) {
// jest doesn't exit if our setup has error here
// https://github.com/facebook/jest/issues/2713
setBeforeAllError(e)
// Closing the page since an error in the setup, for example a runtime error
// when building the playground should skip further tests.
// If the page remains open, a command like `await page.click(...)` produces
// a timeout with an exception that hides the real error in the console.
await page.close()
}
}, 30000)
afterAll(async () => {
global.page?.off('console', onConsole)
global.serverLogs = []
await global.page?.close()
await server?.close()
global.watcher?.close()
const beforeAllErr = getBeforeAllError()
if (beforeAllErr) {
throw beforeAllErr
}
})
function startStaticServer(config?: InlineConfig): Promise<string> {
if (!config) {
// check if the test project has base config
const configFile = resolve(rootDir, 'vite.config.js')
try {
config = require(configFile)
} catch (e) {}
}
// fallback internal base to ''
const base = (config?.base ?? '/') === '/' ? '' : config?.base ?? ''
// @ts-ignore
if (config && config.__test__) {
// @ts-ignore
config.__test__()
}
// start static file server
const serve = sirv(resolve(rootDir, 'dist'), { dev: !!config?.build?.watch })
const httpServer = (server = http.createServer((req, res) => {
if (req.url === '/ping') {
res.statusCode = 200
res.end('pong')
} else {
serve(req, res)
}
}))
let port = 4173
return new Promise((resolve, reject) => {
const onError = (e: any) => {
if (e.code === 'EADDRINUSE') {
httpServer.close()
httpServer.listen(++port)
} else {
reject(e)
}
}
httpServer.on('error', onError)
httpServer.listen(port, () => {
httpServer.removeListener('error', onError)
resolve(`http://localhost:${port}${base}`)
})
})
}
/**
* Send the rebuild complete message in build watch
*/
export async function notifyRebuildComplete(
watcher: RollupWatcher
): Promise<RollupWatcher> {
let callback: (event: RollupWatcherEvent) => void
await new Promise<void>((resolve, reject) => {
callback = (event) => {
if (event.code === 'END') {
resolve()
}
}
watcher.on('event', callback)
})
return watcher.removeListener('event', callback)
}
function createInMemoryLogger(logs: string[]): Logger {
const loggedErrors = new WeakSet<Error | RollupError>()
const warnedMessages = new Set<string>()
const logger: Logger = {
hasWarned: false,
hasErrorLogged: (err) => loggedErrors.has(err),
clearScreen: () => {},
info(msg) {
logs.push(msg)
},
warn(msg) {
logs.push(msg)
logger.hasWarned = true
},
warnOnce(msg) {
if (warnedMessages.has(msg)) return
logs.push(msg)
logger.hasWarned = true
warnedMessages.add(msg)
},
error(msg, opts) {
logs.push(msg)
if (opts?.error) {
loggedErrors.add(opts.error)
}
}
}
return logger
}
function setupConsoleWarnCollector(logs: string[]) {
const warn = console.warn
console.warn = (...args) => {
serverLogs.push(args.join(' '))
return warn.call(console, ...args)
}
}