-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
/
config.ts
487 lines (412 loc) · 15.8 KB
/
config.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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
import { resolveModule } from 'local-pkg'
import { normalize, relative, resolve } from 'pathe'
import c from 'picocolors'
import type { ResolvedConfig as ResolvedViteConfig } from 'vite'
import type { ApiConfig, ResolvedConfig, UserConfig, VitestRunMode } from '../types'
import { defaultBrowserPort, defaultPort, extraInlineDeps } from '../constants'
import { benchmarkConfigDefaults, configDefaults } from '../defaults'
import { isCI, stdProvider, toArray } from '../utils'
import type { BuiltinPool } from '../types/pool-options'
import { VitestCache } from './cache'
import { BaseSequencer } from './sequencers/BaseSequencer'
import { RandomSequencer } from './sequencers/RandomSequencer'
import type { BenchmarkBuiltinReporters } from './reporters'
import { builtinPools } from './pool'
function resolvePath(path: string, root: string) {
return normalize(
resolveModule(path, { paths: [root] })
?? resolve(root, path),
)
}
export function resolveApiServerConfig<Options extends ApiConfig & UserConfig>(
options: Options,
): ApiConfig | undefined {
let api: ApiConfig | undefined
if (options.ui && !options.api)
api = { port: defaultPort }
else if (options.api === true)
api = { port: defaultPort }
else if (typeof options.api === 'number')
api = { port: options.api }
if (typeof options.api === 'object') {
if (api) {
if (options.api.port)
api.port = options.api.port
if (options.api.strictPort)
api.strictPort = options.api.strictPort
if (options.api.host)
api.host = options.api.host
}
else {
api = { ...options.api }
}
}
if (api) {
if (!api.port && !api.middlewareMode)
api.port = defaultPort
}
else {
api = { middlewareMode: true }
}
return api
}
export function resolveConfig(
mode: VitestRunMode,
options: UserConfig,
viteConfig: ResolvedViteConfig,
): ResolvedConfig {
if (options.dom) {
if (
viteConfig.test?.environment != null
&& viteConfig.test!.environment !== 'happy-dom'
) {
console.warn(
c.yellow(
`${c.inverse(c.yellow(' Vitest '))} Your config.test.environment ("${
viteConfig.test.environment
}") conflicts with --dom flag ("happy-dom"), ignoring "${
viteConfig.test.environment
}"`,
),
)
}
options.environment = 'happy-dom'
}
const resolved = {
...configDefaults,
...options,
root: viteConfig.root,
mode,
} as any as ResolvedConfig
resolved.inspect = Boolean(resolved.inspect)
resolved.inspectBrk = Boolean(resolved.inspectBrk)
if (viteConfig.base !== '/')
resolved.base = viteConfig.base
if (options.shard) {
if (resolved.watch)
throw new Error('You cannot use --shard option with enabled watch')
const [indexString, countString] = options.shard.split('/')
const index = Math.abs(Number.parseInt(indexString, 10))
const count = Math.abs(Number.parseInt(countString, 10))
if (Number.isNaN(count) || count <= 0)
throw new Error('--shard <count> must be a positive number')
if (Number.isNaN(index) || index <= 0 || index > count)
throw new Error('--shard <index> must be a positive number less then <count>')
resolved.shard = { index, count }
}
if (resolved.maxWorkers)
resolved.maxWorkers = Number(resolved.maxWorkers)
if (resolved.minWorkers)
resolved.minWorkers = Number(resolved.minWorkers)
resolved.fileParallelism ??= true
if (!resolved.fileParallelism) {
// ignore user config, parallelism cannot be implemented without limiting workers
resolved.maxWorkers = 1
resolved.minWorkers = 1
}
if (resolved.inspect || resolved.inspectBrk) {
const isSingleThread = resolved.pool === 'threads' && resolved.poolOptions?.threads?.singleThread
const isSingleFork = resolved.pool === 'forks' && resolved.poolOptions?.forks?.singleFork
if (resolved.fileParallelism && !isSingleThread && !isSingleFork) {
const inspectOption = `--inspect${resolved.inspectBrk ? '-brk' : ''}`
throw new Error(`You cannot use ${inspectOption} without "--no-file-parallelism", "poolOptions.threads.singleThread" or "poolOptions.forks.singleFork"`)
}
}
// @ts-expect-error -- check for removed API option
if (resolved.coverage.provider === 'c8')
throw new Error('"coverage.provider: c8" is not supported anymore. Use "coverage.provider: v8" instead')
if (resolved.coverage.provider === 'v8' && resolved.coverage.enabled && isBrowserEnabled(resolved))
throw new Error('@vitest/coverage-v8 does not work with --browser. Use @vitest/coverage-istanbul instead')
resolved.deps ??= {}
resolved.deps.moduleDirectories ??= []
resolved.deps.moduleDirectories = resolved.deps.moduleDirectories.map((dir) => {
if (!dir.startsWith('/'))
dir = `/${dir}`
if (!dir.endsWith('/'))
dir += '/'
return normalize(dir)
})
if (!resolved.deps.moduleDirectories.includes('/node_modules/'))
resolved.deps.moduleDirectories.push('/node_modules/')
resolved.deps.optimizer ??= {}
resolved.deps.optimizer.ssr ??= {}
resolved.deps.optimizer.ssr.enabled ??= true
resolved.deps.optimizer.web ??= {}
resolved.deps.optimizer.web.enabled ??= true
resolved.deps.web ??= {}
resolved.deps.web.transformAssets ??= true
resolved.deps.web.transformCss ??= true
resolved.deps.web.transformGlobPattern ??= []
resolved.server ??= {}
resolved.server.deps ??= {}
const deprecatedDepsOptions = ['inline', 'external', 'fallbackCJS'] as const
deprecatedDepsOptions.forEach((option) => {
if (resolved.deps[option] === undefined)
return
if (option === 'fallbackCJS') {
console.warn(c.yellow(`${c.inverse(c.yellow(' Vitest '))} "deps.${option}" is deprecated. Use "server.deps.${option}" instead`))
}
else {
const transformMode = resolved.environment === 'happy-dom' || resolved.environment === 'jsdom' ? 'web' : 'ssr'
console.warn(
c.yellow(
`${c.inverse(c.yellow(' Vitest '))} "deps.${option}" is deprecated. If you rely on vite-node directly, use "server.deps.${option}" instead. Otherwise, consider using "deps.optimizer.${transformMode}.${option === 'external' ? 'exclude' : 'include'}"`,
),
)
}
if (resolved.server.deps![option] === undefined)
resolved.server.deps![option] = resolved.deps[option] as any
})
if (resolved.cliExclude)
resolved.exclude.push(...resolved.cliExclude)
// vitenode will try to import such file with native node,
// but then our mocker will not work properly
if (resolved.server.deps.inline !== true) {
const ssrOptions = viteConfig.ssr
if (ssrOptions?.noExternal === true && resolved.server.deps.inline == null) {
resolved.server.deps.inline = true
}
else {
resolved.server.deps.inline ??= []
resolved.server.deps.inline.push(...extraInlineDeps)
}
}
resolved.server.deps.moduleDirectories ??= []
resolved.server.deps.moduleDirectories.push(...resolved.deps.moduleDirectories)
if (resolved.runner)
resolved.runner = resolvePath(resolved.runner, resolved.root)
resolved.testNamePattern = resolved.testNamePattern
? resolved.testNamePattern instanceof RegExp
? resolved.testNamePattern
: new RegExp(resolved.testNamePattern)
: undefined
if (resolved.snapshotFormat && 'plugins' in resolved.snapshotFormat)
(resolved.snapshotFormat as any).plugins = []
const UPDATE_SNAPSHOT = resolved.update || process.env.UPDATE_SNAPSHOT
resolved.snapshotOptions = {
expand: resolved.expandSnapshotDiff ?? false,
snapshotFormat: resolved.snapshotFormat || {},
updateSnapshot: (isCI && !UPDATE_SNAPSHOT)
? 'none'
: UPDATE_SNAPSHOT
? 'all'
: 'new',
resolveSnapshotPath: options.resolveSnapshotPath,
// resolved inside the worker
snapshotEnvironment: null as any,
}
resolved.snapshotSerializers ??= []
resolved.snapshotSerializers = resolved.snapshotSerializers.map(file =>
resolvePath(file, resolved.root),
)
resolved.forceRerunTriggers.push(...resolved.snapshotSerializers)
if (options.resolveSnapshotPath)
delete (resolved as UserConfig).resolveSnapshotPath
resolved.pool ??= 'threads'
if (process.env.VITEST_MAX_THREADS) {
resolved.poolOptions = {
...resolved.poolOptions,
threads: {
...resolved.poolOptions?.threads,
maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS),
},
vmThreads: {
...resolved.poolOptions?.vmThreads,
maxThreads: Number.parseInt(process.env.VITEST_MAX_THREADS),
},
}
}
if (process.env.VITEST_MIN_THREADS) {
resolved.poolOptions = {
...resolved.poolOptions,
threads: {
...resolved.poolOptions?.threads,
minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS),
},
vmThreads: {
...resolved.poolOptions?.vmThreads,
minThreads: Number.parseInt(process.env.VITEST_MIN_THREADS),
},
}
}
if (process.env.VITEST_MAX_FORKS) {
resolved.poolOptions = {
...resolved.poolOptions,
forks: {
...resolved.poolOptions?.forks,
maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS),
},
vmForks: {
...resolved.poolOptions?.vmForks,
maxForks: Number.parseInt(process.env.VITEST_MAX_FORKS),
},
}
}
if (process.env.VITEST_MIN_FORKS) {
resolved.poolOptions = {
...resolved.poolOptions,
forks: {
...resolved.poolOptions?.forks,
minForks: Number.parseInt(process.env.VITEST_MIN_FORKS),
},
vmForks: {
...resolved.poolOptions?.vmForks,
minForks: Number.parseInt(process.env.VITEST_MIN_FORKS),
},
}
}
if (resolved.workspace) {
// if passed down from the CLI and it's relative, resolve relative to CWD
resolved.workspace = options.workspace && options.workspace[0] === '.'
? resolve(process.cwd(), options.workspace)
: resolvePath(resolved.workspace, resolved.root)
}
if (!builtinPools.includes(resolved.pool as BuiltinPool))
resolved.pool = resolvePath(resolved.pool, resolved.root)
resolved.poolMatchGlobs = (resolved.poolMatchGlobs || []).map(([glob, pool]) => {
if (!builtinPools.includes(pool as BuiltinPool))
pool = resolvePath(pool, resolved.root)
return [glob, pool]
})
if (mode === 'benchmark') {
resolved.benchmark = {
...benchmarkConfigDefaults,
...resolved.benchmark,
}
// override test config
resolved.coverage.enabled = false
resolved.include = resolved.benchmark.include
resolved.exclude = resolved.benchmark.exclude
resolved.includeSource = resolved.benchmark.includeSource
const reporters = Array.from(new Set<BenchmarkBuiltinReporters>([
...toArray(resolved.benchmark.reporters),
// @ts-expect-error reporter is CLI flag
...toArray(options.reporter),
])).filter(Boolean)
if (reporters.length)
resolved.benchmark.reporters = reporters
else
resolved.benchmark.reporters = ['default']
if (options.outputFile)
resolved.benchmark.outputFile = options.outputFile
}
resolved.setupFiles = toArray(resolved.setupFiles || []).map(file =>
resolvePath(file, resolved.root),
)
resolved.globalSetup = toArray(resolved.globalSetup || []).map(file =>
resolvePath(file, resolved.root),
)
resolved.coverage.exclude.push(...resolved.setupFiles.map(file => `${resolved.coverage.allowExternal ? '**/' : ''}${relative(resolved.root, file)}`))
resolved.forceRerunTriggers = [
...resolved.forceRerunTriggers,
...resolved.setupFiles,
]
if (resolved.diff) {
resolved.diff = resolvePath(resolved.diff, resolved.root)
resolved.forceRerunTriggers.push(resolved.diff)
}
// the server has been created, we don't need to override vite.server options
resolved.api = resolveApiServerConfig(options)
if (options.related)
resolved.related = toArray(options.related).map(file => resolve(resolved.root, file))
/*
* Reporters can be defined in many different ways:
* { reporter: 'json' }
* { reporter: { onFinish() { method() } } }
* { reporter: ['json', { onFinish() { method() } }] }
* { reporter: [[ 'json' ]] }
* { reporter: [[ 'json' ], 'html'] }
* { reporter: [[ 'json', { outputFile: 'test.json' } ], 'html'] }
*/
if (options.reporters) {
if (!Array.isArray(options.reporters)) {
// Reporter name, e.g. { reporters: 'json' }
if (typeof options.reporters === 'string')
resolved.reporters = [[options.reporters, {}]]
// Inline reporter e.g. { reporters: { onFinish() { method() } } }
else
resolved.reporters = [options.reporters]
}
// It's an array of reporters
else {
resolved.reporters = []
for (const reporter of options.reporters) {
if (Array.isArray(reporter)) {
// Reporter with options, e.g. { reporters: [ [ 'json', { outputFile: 'test.json' } ] ] }
resolved.reporters.push([reporter[0], reporter[1] || {}])
}
else if (typeof reporter === 'string') {
// Reporter name in array, e.g. { reporters: ["html", "json"]}
resolved.reporters.push([reporter, {}])
}
else {
// Inline reporter, e.g. { reporter: [{ onFinish() { method() } }] }
resolved.reporters.push(reporter)
}
}
}
}
if (mode !== 'benchmark') {
// @ts-expect-error "reporter" is from CLI, should be absolute to the running directory
// it is passed down as "vitest --reporter ../reporter.js"
const reportersFromCLI = resolved.reporter
const cliReporters = toArray(reportersFromCLI || []).map((reporter: string) => {
// ./reporter.js || ../reporter.js, but not .reporters/reporter.js
if (/^\.\.?\//.test(reporter))
return resolve(process.cwd(), reporter)
return reporter
})
if (cliReporters.length)
resolved.reporters = Array.from(new Set(toArray(cliReporters))).filter(Boolean).map(reporter => [reporter, {}])
}
if (!resolved.reporters.length) {
resolved.reporters.push(['default', {}])
// also enable github-actions reporter as a default
if (process.env.GITHUB_ACTIONS === 'true')
resolved.reporters.push(['github-actions', {}])
}
if (resolved.changed)
resolved.passWithNoTests ??= true
resolved.css ??= {}
if (typeof resolved.css === 'object') {
resolved.css.modules ??= {}
resolved.css.modules.classNameStrategy ??= 'stable'
}
resolved.cache ??= { dir: '' }
if (resolved.cache)
resolved.cache.dir = VitestCache.resolveCacheDir(resolved.root, resolved.cache.dir, resolved.name)
resolved.sequence ??= {} as any
if (!resolved.sequence?.sequencer) {
// CLI flag has higher priority
resolved.sequence.sequencer = resolved.sequence.shuffle
? RandomSequencer
: BaseSequencer
}
resolved.sequence.hooks ??= 'parallel'
if (resolved.sequence.sequencer === RandomSequencer)
resolved.sequence.seed ??= Date.now()
resolved.typecheck = {
...configDefaults.typecheck,
...resolved.typecheck,
}
resolved.environmentMatchGlobs = (resolved.environmentMatchGlobs || []).map(i => [resolve(resolved.root, i[0]), i[1]])
resolved.typecheck ??= {} as any
resolved.typecheck.enabled ??= false
if (resolved.typecheck.enabled)
console.warn(c.yellow('Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest\'s version when using it.'))
resolved.browser ??= {} as any
resolved.browser.enabled ??= false
resolved.browser.headless ??= isCI
resolved.browser.slowHijackESM ??= false
resolved.browser.isolate ??= true
if (resolved.browser.enabled && stdProvider === 'stackblitz')
resolved.browser.provider = 'none'
resolved.browser.api = resolveApiServerConfig(resolved.browser) || {
port: defaultBrowserPort,
}
resolved.testTransformMode ??= {}
return resolved
}
export function isBrowserEnabled(config: ResolvedConfig): boolean {
return Boolean(config.browser?.enabled)
}