forked from vitest-dev/vitest
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcore.ts
More file actions
1493 lines (1300 loc) · 49.9 KB
/
core.ts
File metadata and controls
1493 lines (1300 loc) · 49.9 KB
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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { CancelReason, File } from '@vitest/runner'
import type { Awaitable } from '@vitest/utils'
import type { Writable } from 'node:stream'
import type { ViteDevServer } from 'vite'
import type { ModuleRunner } from 'vite/module-runner'
import type { SerializedCoverageConfig } from '../runtime/config'
import type { ArgumentsType, ProvidedContext, UserConsoleLog } from '../types/general'
import type { SourceModuleDiagnostic, SourceModuleLocations } from '../types/module-locations'
import type { CliOptions } from './cli/cli-api'
import type { VitestFetchFunction } from './environments/fetchModule'
import type { ProcessPool } from './pool'
import type { TestModule } from './reporters/reported-tasks'
import type { TestSpecification } from './test-specification'
import type { ResolvedConfig, TestProjectConfiguration, UserConfig, VitestRunMode } from './types/config'
import type { CoverageProvider, ResolvedCoverageOptions } from './types/coverage'
import type { Reporter } from './types/reporter'
import type { TestRunResult } from './types/tests'
import os, { tmpdir } from 'node:os'
import { getTasks, hasFailed, limitConcurrency } from '@vitest/runner/utils'
import { SnapshotManager } from '@vitest/snapshot/manager'
import { deepClone, deepMerge, nanoid, noop, toArray } from '@vitest/utils/helpers'
import { join, normalize, relative } from 'pathe'
import { version } from '../../package.json' with { type: 'json' }
import { WebSocketReporter } from '../api/setup'
import { distDir } from '../paths'
import { wildcardPatternToRegExp } from '../utils/base'
import { convertTasksToEvents } from '../utils/tasks'
import { Traces } from '../utils/traces'
import { astCollectTests, createFailedFileTask } from './ast-collect'
import { BrowserSessions } from './browser/sessions'
import { VitestCache } from './cache'
import { FileSystemModuleCache } from './cache/fsModuleCache'
import { resolveConfig } from './config/resolveConfig'
import { getCoverageProvider } from './coverage'
import { createFetchModuleFunction } from './environments/fetchModule'
import { ServerModuleRunner } from './environments/serverRunner'
import { FilesNotFoundError } from './errors'
import { Logger } from './logger'
import { collectModuleDurationsDiagnostic, collectSourceModulesLocations } from './module-diagnostic'
import { VitestPackageInstaller } from './packageInstaller'
import { createPool } from './pool'
import { TestProject } from './project'
import { getDefaultTestProject, resolveBrowserProjects, resolveProjects } from './projects/resolveProjects'
import { BlobReporter, readBlobs } from './reporters/blob'
import { HangingProcessReporter } from './reporters/hanging-process'
import { createBenchmarkReporters, createReporters } from './reporters/utils'
import { VitestResolver } from './resolver'
import { VitestSpecifications } from './specifications'
import { StateManager } from './state'
import { TestRun } from './test-run'
import { VitestWatcher } from './watcher'
const WATCHER_DEBOUNCE = 100
export interface VitestOptions {
packageInstaller?: VitestPackageInstaller
stdin?: NodeJS.ReadStream
stdout?: NodeJS.WriteStream | Writable
stderr?: NodeJS.WriteStream | Writable
}
export class Vitest {
/**
* Current Vitest version.
* @example '2.0.0'
*/
public readonly version: string = version
static readonly version: string = version
/**
* The logger instance used to log messages. It's recommended to use this logger instead of `console`.
* It's possible to override stdout and stderr streams when initiating Vitest.
* @example
* new Vitest('test', {
* stdout: new Writable(),
* })
*/
public readonly logger: Logger
/**
* The package installer instance used to install Vitest packages.
* @example
* await vitest.packageInstaller.ensureInstalled('@vitest/browser', process.cwd())
*/
public readonly packageInstaller: VitestPackageInstaller
/**
* A path to the built Vitest directory. This is usually a folder in `node_modules`.
*/
public readonly distPath: string = distDir
/**
* A list of projects that are currently running.
* If projects were filtered with `--project` flag, they won't appear here.
*/
public projects: TestProject[] = []
/**
* A watcher handler. This is not the file system watcher. The handler only
* exposes methods to handle changed files.
*
* If you have your own watcher, you can use these methods to replicate
* Vitest behaviour.
*/
public readonly watcher: VitestWatcher
/** @internal */ configOverride: Partial<ResolvedConfig> = {}
/** @internal */ filenamePattern?: string[]
/** @internal */ runningPromise?: Promise<TestRunResult>
/** @internal */ closingPromise?: Promise<void>
/** @internal */ cancelPromise?: Promise<void | void[]>
/** @internal */ isCancelling = false
/** @internal */ coreWorkspaceProject: TestProject | undefined
/** @internal */ _browserSessions = new BrowserSessions()
/** @internal */ _cliOptions: CliOptions = {}
/** @internal */ reporters: Reporter[] = []
/** @internal */ runner!: ModuleRunner
/** @internal */ _testRun: TestRun = undefined!
/** @internal */ _resolver!: VitestResolver
/** @internal */ _fetcher!: VitestFetchFunction
/** @internal */ _fsCache!: FileSystemModuleCache
/** @internal */ _tmpDir = join(tmpdir(), nanoid())
/** @internal */ _traces!: Traces
private isFirstRun = true
private restartsCount = 0
private readonly specifications: VitestSpecifications
private pool: ProcessPool | undefined
private _config?: ResolvedConfig
private _vite?: ViteDevServer
private _state?: StateManager
private _cache?: VitestCache
private _snapshot?: SnapshotManager
private _coverageProvider?: CoverageProvider | null | undefined
constructor(
public readonly mode: VitestRunMode,
cliOptions: UserConfig,
options: VitestOptions = {},
) {
this._cliOptions = cliOptions
this.logger = new Logger(this, options.stdout, options.stderr)
this.packageInstaller = options.packageInstaller || new VitestPackageInstaller()
this.specifications = new VitestSpecifications(this)
this.watcher = new VitestWatcher(this).onWatcherRerun(file =>
this.scheduleRerun(file), // TODO: error handling
)
}
private _onRestartListeners: OnServerRestartHandler[] = []
private _onClose: (() => Awaitable<void>)[] = []
private _onSetServer: OnServerRestartHandler[] = []
private _onCancelListeners = new Set<(reason: CancelReason) => Awaitable<void>>()
private _onUserTestsRerun: OnTestsRerunHandler[] = []
private _onFilterWatchedSpecification: ((spec: TestSpecification) => boolean)[] = []
/**
* The global config.
*/
get config(): ResolvedConfig {
assert(this._config, 'config')
return this._config
}
/**
* Global Vite's dev server instance.
*/
get vite(): ViteDevServer {
assert(this._vite, 'vite', 'server')
return this._vite
}
/**
* The global test state manager.
* @experimental The State API is experimental and not subject to semver.
*/
get state(): StateManager {
assert(this._state, 'state')
return this._state
}
/**
* The global snapshot manager. You can access the current state on `snapshot.summary`.
*/
get snapshot(): SnapshotManager {
assert(this._snapshot, 'snapshot', 'snapshot manager')
return this._snapshot
}
/**
* Test results and test file stats cache. Primarily used by the sequencer to sort tests.
*/
get cache(): VitestCache {
assert(this._cache, 'cache')
return this._cache
}
/** @internal */
async _setServer(options: UserConfig, server: ViteDevServer) {
this.watcher.unregisterWatcher()
clearTimeout(this._rerunTimer)
this.restartsCount += 1
this.pool?.close?.()
this.pool = undefined
this.closingPromise = undefined
this.projects = []
this.runningPromise = undefined
this.coreWorkspaceProject = undefined
this.specifications.clearCache()
this._coverageProvider = undefined
this._onUserTestsRerun = []
this._vite = server
const resolved = resolveConfig(this, options, server.config)
this._config = resolved
this._state = new StateManager({
onUnhandledError: resolved.onUnhandledError,
})
this._cache = new VitestCache(this.logger)
this._snapshot = new SnapshotManager({ ...resolved.snapshotOptions })
this._testRun = new TestRun(this)
const otelSdkPath = resolved.experimental.openTelemetry?.sdkPath
this._traces = new Traces({
enabled: !!resolved.experimental.openTelemetry?.enabled,
sdkPath: otelSdkPath,
watchMode: resolved.watch,
})
if (this.config.watch) {
this.watcher.registerWatcher()
}
this._resolver = new VitestResolver(server.config.cacheDir, resolved)
this._fsCache = new FileSystemModuleCache(this)
this._fetcher = createFetchModuleFunction(
this._resolver,
this._config,
this._fsCache,
this._traces,
this._tmpDir,
)
const environment = server.environments.__vitest__
this.runner = new ServerModuleRunner(
environment,
this._fetcher,
resolved,
)
if (this.config.watch) {
// hijack server restart
const serverRestart = server.restart
server.restart = async (...args) => {
await Promise.all(this._onRestartListeners.map(fn => fn()))
this.report('onServerRestart')
await this.close()
await serverRestart(...args)
}
// since we set `server.hmr: false`, Vite does not auto restart itself
server.watcher.on('change', async (file) => {
file = normalize(file)
const isConfig = file === server.config.configFile
|| this.projects.some(p => p.vite.config.configFile === file)
if (isConfig) {
await Promise.all(this._onRestartListeners.map(fn => fn('config')))
this.report('onServerRestart', 'config')
await this.close()
await serverRestart()
}
})
}
this.cache.results.setConfig(resolved.root, resolved.cache)
try {
await this.cache.results.readFromCache()
}
catch { }
const projects = await this.resolveProjects(this._cliOptions)
this.projects = projects
await Promise.all(projects.flatMap((project) => {
const hooks = project.vite.config.getSortedPluginHooks('configureVitest')
return hooks.map(hook => hook({
project,
vitest: this,
injectTestProjects: this.injectTestProject,
/**
* @experimental
*/
experimental_defineCacheKeyGenerator: callback => this._fsCache.defineCacheKeyGenerator(callback),
}))
}))
if (this._cliOptions.browser?.enabled) {
const browserProjects = this.projects.filter(p => p.config.browser.enabled)
if (!browserProjects.length) {
throw new Error(`Vitest received --browser flag, but no project had a browser configuration.`)
}
}
if (!this.projects.length) {
const filter = toArray(resolved.project).join('", "')
if (filter) {
throw new Error(`No projects matched the filter "${filter}".`)
}
else {
let error = `Vitest wasn't able to resolve any project.`
if (this.config.browser.enabled && !this.config.browser.instances?.length) {
error += ` Please, check that you specified the "browser.instances" option.`
}
throw new Error(error)
}
}
if (!this.coreWorkspaceProject) {
this.coreWorkspaceProject = TestProject._createBasicProject(this)
}
if (this.config.testNamePattern) {
this.configOverride.testNamePattern = this.config.testNamePattern
}
this.reporters = resolved.mode === 'benchmark'
? await createBenchmarkReporters(toArray(resolved.benchmark?.reporters), this.runner)
: await createReporters(resolved.reporters, this)
await this._fsCache.ensureCacheIntegrity()
await Promise.all([
...this._onSetServer.map(fn => fn()),
this._traces.waitInit(),
])
}
/** @internal */
get coverageProvider(): CoverageProvider | null | undefined {
if (this.configOverride.coverage?.enabled === false) {
return null
}
return this._coverageProvider
}
public async enableCoverage(): Promise<void> {
this.configOverride.coverage = {} as any
this.configOverride.coverage!.enabled = true
await this.createCoverageProvider()
await this.coverageProvider?.onEnabled?.()
// onFileTransform is the only thing that affects hash
if (this.coverageProvider?.onFileTransform) {
this.clearAllCachePaths()
}
}
public disableCoverage(): void {
this.configOverride.coverage ??= {} as any
this.configOverride.coverage!.enabled = false
// onFileTransform is the only thing that affects hash
if (this.coverageProvider?.onFileTransform) {
this.clearAllCachePaths()
}
}
private clearAllCachePaths() {
this.projects.forEach(({ vite, browser }) => {
const environments = [
...Object.values(vite.environments),
...Object.values(browser?.vite.environments || {}),
]
environments.forEach(environment =>
this._fsCache.invalidateAllCachePaths(environment),
)
})
}
private _coverageOverrideCache = new WeakMap<ResolvedCoverageOptions, ResolvedCoverageOptions>()
/** @internal */
get _coverageOptions(): ResolvedCoverageOptions {
if (!this.configOverride.coverage) {
return this.config.coverage
}
if (!this._coverageOverrideCache.has(this.configOverride.coverage)) {
const coverage = deepClone(this.config.coverage)
const options = deepMerge(coverage, this.configOverride.coverage)
this._coverageOverrideCache.set(
this.configOverride.coverage,
options,
)
}
return this._coverageOverrideCache.get(this.configOverride.coverage)!
}
/**
* Inject new test projects into the workspace.
* @param config Glob, config path or a custom config options.
* @returns An array of new test projects. Can be empty if the name was filtered out.
*/
private injectTestProject = async (config: TestProjectConfiguration | TestProjectConfiguration[]): Promise<TestProject[]> => {
const currentNames = new Set(this.projects.map(p => p.name))
const projects = await resolveProjects(
this,
this._cliOptions,
undefined,
Array.isArray(config) ? config : [config],
currentNames,
)
this.projects.push(...projects)
return projects
}
/**
* Provide a value to the test context. This value will be available to all tests with `inject`.
*/
public provide = <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]): void => {
this.getRootProject().provide(key, value)
}
/**
* Get global provided context.
*/
public getProvidedContext(): ProvidedContext {
return this.getRootProject().getProvidedContext()
}
/** @internal */
_ensureRootProject(): TestProject {
if (this.coreWorkspaceProject) {
return this.coreWorkspaceProject
}
this.coreWorkspaceProject = TestProject._createBasicProject(this)
return this.coreWorkspaceProject
}
/**
* Return project that has the root (or "global") config.
*/
public getRootProject(): TestProject {
if (!this.coreWorkspaceProject) {
throw new Error(`Root project is not initialized. This means that the Vite server was not established yet and the the workspace config is not resolved.`)
}
return this.coreWorkspaceProject
}
public getProjectByName(name: string): TestProject {
const project = this.projects.find(p => p.name === name)
|| this.coreWorkspaceProject
|| this.projects[0]
if (!project) {
throw new Error(`Project "${name}" was not found.`)
}
return project
}
/**
* Import a file using Vite module runner. The file will be transformed by Vite and executed in a separate context.
* @param moduleId The ID of the module in Vite module graph
*/
public import<T>(moduleId: string): Promise<T> {
return this.runner.import(moduleId)
}
/**
* Creates a coverage provider if `coverage` is enabled in the config.
*/
public async createCoverageProvider(): Promise<CoverageProvider | null> {
if (this._coverageProvider) {
return this._coverageProvider
}
const coverageProvider = await this.initCoverageProvider()
if (coverageProvider) {
await coverageProvider.clean(this._coverageOptions.clean)
}
return coverageProvider || null
}
private async resolveProjects(cliOptions: UserConfig): Promise<TestProject[]> {
const names = new Set<string>()
if (this.config.projects) {
return resolveProjects(
this,
cliOptions,
undefined,
this.config.projects,
names,
)
}
if ('workspace' in this.config) {
throw new Error('The `test.workspace` option was removed in Vitest 4. Please, migrate to `test.projects` instead. See https://vitest.dev/guide/projects for examples.')
}
// user can filter projects with --project flag, `getDefaultTestProject`
// returns the project only if it matches the filter
const project = getDefaultTestProject(this)
if (!project) {
return []
}
return resolveBrowserProjects(this, new Set([project.name]), [project])
}
/**
* Glob test files in every project and create a TestSpecification for each file and pool.
* @param filters String filters to match the test files.
*/
public async globTestSpecifications(filters: string[] = []): Promise<TestSpecification[]> {
return this.specifications.globTestSpecifications(filters)
}
private async initCoverageProvider(): Promise<CoverageProvider | null | undefined> {
if (this._coverageProvider != null) {
return
}
const coverageConfig = (this.configOverride.coverage
? this.getRootProject().serializedConfig.coverage
: this.config.coverage) as unknown as SerializedCoverageConfig
this._coverageProvider = await getCoverageProvider(
coverageConfig,
this.runner,
)
if (this._coverageProvider) {
await this._coverageProvider.initialize(this)
this.config.coverage = this._coverageProvider.resolveOptions()
}
return this._coverageProvider
}
/**
* Deletes all Vitest caches, including `experimental.fsModuleCache`.
* @experimental
*/
public async experimental_clearCache(): Promise<void> {
await this.cache.results.clearCache()
await this._fsCache.clearCache()
}
/**
* Merge reports from multiple runs located in the specified directory (value from `--merge-reports` if not specified).
*/
public async mergeReports(directory?: string): Promise<TestRunResult> {
return this._traces.$('vitest.merge_reports', async () => {
if (this.reporters.some(r => r instanceof BlobReporter)) {
throw new Error('Cannot merge reports when `--reporter=blob` is used. Remove blob reporter from the config first.')
}
const { files, errors, coverages, executionTimes } = await readBlobs(this.version, directory || this.config.mergeReports, this.projects)
this.state.blobs = { files, errors, coverages, executionTimes }
await this.report('onInit', this)
const specifications: TestSpecification[] = []
for (const file of files) {
const project = this.getProjectByName(file.projectName || '')
const specification = project.createSpecification(file.filepath, undefined, file.pool)
specifications.push(specification)
}
await this._testRun.start(specifications).catch(noop)
for (const file of files) {
await this._reportFileTask(file)
}
this._checkUnhandledErrors(errors)
await this._testRun.end(specifications, errors).catch(noop)
await this.initCoverageProvider()
await this.coverageProvider?.mergeReports?.(coverages)
return {
testModules: this.state.getTestModules(),
unhandledErrors: this.state.getUnhandledErrors(),
}
})
}
/**
* Returns the seed, if tests are running in a random order.
*/
public getSeed(): number | null {
return this.config.sequence.seed ?? null
}
/** @internal */
public async _reportFileTask(file: File): Promise<void> {
const project = this.getProjectByName(file.projectName || '')
await this._testRun.enqueued(project, file).catch(noop)
await this._testRun.collected(project, [file]).catch(noop)
const logs: UserConsoleLog[] = []
const { packs, events } = convertTasksToEvents(file, (task) => {
if (task.logs) {
logs.push(...task.logs)
}
})
logs.sort((log1, log2) => log1.time - log2.time)
for (const log of logs) {
await this._testRun.log(log).catch(noop)
}
await this._testRun.updated(packs, events).catch(noop)
}
async collect(filters?: string[]): Promise<TestRunResult> {
return this._traces.$('vitest.collect', async (collectSpan) => {
const filenamePattern = filters && filters?.length > 0 ? filters : []
collectSpan.setAttribute('vitest.collect.filters', filenamePattern)
const files = await this._traces.$(
'vitest.config.resolve_include_glob',
async () => {
const specifications = await this.specifications.getRelevantTestSpecifications(filters)
collectSpan.setAttribute(
'vitest.collect.specifications',
specifications.map((s) => {
const relativeModuleId = relative(s.project.config.root, s.moduleId)
if (s.project.name) {
return `|${s.project.name}| ${relativeModuleId}`
}
return relativeModuleId
}),
)
return specifications
},
)
// if run with --changed, don't exit if no tests are found
if (!files.length) {
return { testModules: [], unhandledErrors: [] }
}
return this.collectTests(files)
})
}
/**
* Returns the list of test files that match the config and filters.
* @param filters String filters to match the test files
*/
getRelevantTestSpecifications(filters?: string[]): Promise<TestSpecification[]> {
return this.specifications.getRelevantTestSpecifications(filters)
}
/**
* Initialize reporters, the coverage provider, and run tests.
* This method can throw an error:
* - `FilesNotFoundError` if no tests are found
* - `GitNotFoundError` if `--related` flag is used, but git repository is not initialized
* - `Error` from the user reporters
* @param filters String filters to match the test files
*/
async start(filters?: string[]): Promise<TestRunResult> {
return this._traces.$('vitest.start', { context: this._traces.getContextFromEnv(process.env) }, async (startSpan) => {
startSpan.setAttributes({
config: this.vite.config.configFile,
})
try {
await this._traces.$('vitest.coverage.init', async () => {
await this.initCoverageProvider()
await this.coverageProvider?.clean(this._coverageOptions.clean)
})
}
finally {
await this.report('onInit', this)
}
this.filenamePattern = filters && filters?.length > 0 ? filters : undefined
startSpan.setAttribute('vitest.start.filters', this.filenamePattern || [])
const specifications = await this._traces.$(
'vitest.config.resolve_include_glob',
async () => {
const specifications = await this.specifications.getRelevantTestSpecifications(filters)
startSpan.setAttribute(
'vitest.start.specifications',
specifications.map((s) => {
const relativeModuleId = relative(s.project.config.root, s.moduleId)
if (s.project.name) {
return `|${s.project.name}| ${relativeModuleId}`
}
return relativeModuleId
}),
)
return specifications
},
)
// if run with --changed, don't exit if no tests are found
if (!specifications.length) {
await this._traces.$('vitest.test_run', async () => {
await this._testRun.start([])
const coverage = await this.coverageProvider?.generateCoverage?.({ allTestsRun: true })
await this._testRun.end([], [], coverage)
// Report coverage for uncovered files
await this.reportCoverage(coverage, true)
})
if (!this.config.watch || !(this.config.changed || this.config.related?.length)) {
throw new FilesNotFoundError(this.mode)
}
}
let testModules: TestRunResult = {
testModules: [],
unhandledErrors: [],
}
if (specifications.length) {
// populate once, update cache on watch
await this.cache.stats.populateStats(this.config.root, specifications)
testModules = await this.runFiles(specifications, true)
}
if (this.config.watch) {
await this.report('onWatcherStart')
}
return testModules
})
}
/**
* Initialize reporters and the coverage provider. This method doesn't run any tests.
* If the `--watch` flag is provided, Vitest will still run changed tests even if this method was not called.
*/
async init(): Promise<void> {
await this._traces.$('vitest.init', async () => {
try {
await this.initCoverageProvider()
await this.coverageProvider?.clean(this._coverageOptions.clean)
}
finally {
await this.report('onInit', this)
}
// populate test files cache so watch mode can trigger a file rerun
await this.globTestSpecifications()
if (this.config.watch) {
await this.report('onWatcherStart')
}
})
}
/**
* If there is a test run happening, returns a promise that will
* resolve when the test run is finished.
*/
public async waitForTestRunEnd(): Promise<void> {
if (!this.runningPromise) {
return
}
await this.runningPromise
}
/**
* Get test specifications associated with the given module. If module is not a test file, an empty array is returned.
*
* **Note:** this method relies on a cache generated by `globTestSpecifications`. If the file was not processed yet, use `project.matchesGlobPattern` instead.
* @param moduleId The module ID to get test specifications for.
*/
public getModuleSpecifications(moduleId: string): TestSpecification[] {
return this.specifications.getModuleSpecifications(moduleId)
}
/**
* Vitest automatically caches test specifications for each file. This method clears the cache for the given file or the whole cache altogether.
*/
public clearSpecificationsCache(moduleId?: string): void {
this.specifications.clearCache(moduleId)
if (!moduleId) {
this.projects.forEach((project) => {
project.testFilesList = null
})
}
}
/**
* Run tests for the given test specifications. This does not trigger `onWatcher*` events.
* @param specifications A list of specifications to run.
* @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
*/
public runTestSpecifications(specifications: TestSpecification[], allTestsRun = false): Promise<TestRunResult> {
specifications.forEach(spec => this.specifications.ensureSpecificationCached(spec))
return this.runFiles(specifications, allTestsRun)
}
/**
* Runs tests for the given file paths. This does not trigger `onWatcher*` events.
* @param filepaths A list of file paths to run tests for.
* @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
*/
public async runTestFiles(filepaths: string[], allTestsRun = false): Promise<TestRunResult> {
const specifications = await this.specifications.getRelevantTestSpecifications(filepaths)
if (!specifications.length) {
return { testModules: [], unhandledErrors: [] }
}
return this.runFiles(specifications, allTestsRun)
}
/**
* Rerun files and trigger `onWatcherRerun`, `onWatcherStart` and `onTestsRerun` events.
* @param specifications A list of specifications to run.
* @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
*/
public async rerunTestSpecifications(specifications: TestSpecification[], allTestsRun = false): Promise<TestRunResult> {
const files = specifications.map(spec => spec.moduleId)
await Promise.all([
this.report('onWatcherRerun', files, 'rerun test'),
...this._onUserTestsRerun.map(fn => fn(specifications)),
])
const result = await this.runTestSpecifications(specifications, allTestsRun)
await this.report('onWatcherStart', this.state.getFiles(files))
return result
}
private async runFiles(specs: TestSpecification[], allTestsRun: boolean): Promise<TestRunResult> {
return this._traces.$('vitest.test_run', async () => {
await this._testRun.start(specs)
// previous run
await this.cancelPromise
await this.runningPromise
this._onCancelListeners.clear()
this.isCancelling = false
// schedule the new run
this.runningPromise = (async () => {
try {
if (!this.pool) {
this.pool = createPool(this)
}
const invalidates = Array.from(this.watcher.invalidates)
this.watcher.invalidates.clear()
this.snapshot.clear()
this.state.clearErrors()
if (!this.isFirstRun && this._coverageOptions.cleanOnRerun) {
await this.coverageProvider?.clean()
}
await this.initializeGlobalSetup(specs)
try {
await this.pool.runTests(specs, invalidates)
}
catch (err) {
this.state.catchError(err, 'Unhandled Error')
}
const files = this.state.getFiles()
this.cache.results.updateResults(files)
try {
await this.cache.results.writeToCache()
}
catch {}
return {
testModules: this.state.getTestModules(),
unhandledErrors: this.state.getUnhandledErrors(),
}
}
finally {
const coverage = await this.coverageProvider?.generateCoverage({ allTestsRun })
const errors = this.state.getUnhandledErrors()
this._checkUnhandledErrors(errors)
await this._testRun.end(specs, errors, coverage)
await this.reportCoverage(coverage, allTestsRun)
}
})()
.finally(() => {
this.runningPromise = undefined
this.isFirstRun = false
// all subsequent runs will treat this as a fresh run
this.config.changed = false
this.config.related = undefined
})
return await this.runningPromise
})
}
/**
* Returns module's diagnostic. If `testModule` is not provided, `selfTime` and `totalTime` will be aggregated across all tests.
*
* If the module was not transformed or executed, the diagnostic will be empty.
* @experimental
* @see {@link https://vitest.dev/api/advanced/vitest#getsourcemodulediagnostic}
*/
public async experimental_getSourceModuleDiagnostic(moduleId: string, testModule?: TestModule): Promise<SourceModuleDiagnostic> {
if (testModule) {
const viteEnvironment = testModule.viteEnvironment
// if there is no viteEnvironment, it means the file did not run yet
if (!viteEnvironment) {
return { modules: [], untrackedModules: [] }
}
const moduleLocations = await collectSourceModulesLocations(moduleId, viteEnvironment.moduleGraph)
return collectModuleDurationsDiagnostic(moduleId, this.state, moduleLocations, testModule)
}
const environments = this.projects.flatMap((p) => {
return Object.values(p.vite.environments)
})
const aggregatedLocationsResult = await Promise.all(
environments.map(environment =>
collectSourceModulesLocations(moduleId, environment.moduleGraph),
),
)
return collectModuleDurationsDiagnostic(
moduleId,
this.state,
aggregatedLocationsResult.reduce<SourceModuleLocations>((acc, locations) => {
if (locations) {
acc.modules.push(...locations.modules)
acc.untracked.push(...locations.untracked)
}
return acc
}, { modules: [], untracked: [] }),
)
}
public async experimental_parseSpecifications(specifications: TestSpecification[], options?: {
/** @default os.availableParallelism() */
concurrency?: number
}): Promise<TestModule[]> {
if (this.mode !== 'test') {
throw new Error(`The \`experimental_parseSpecifications\` does not support "${this.mode}" mode.`)
}
const concurrency = options?.concurrency ?? (typeof os.availableParallelism === 'function'
? os.availableParallelism()
: os.cpus().length)
const limit = limitConcurrency(concurrency)
const promises = specifications.map(specification =>
limit(() => this.experimental_parseSpecification(specification)),
)
return Promise.all(promises)
}
public async experimental_parseSpecification(specification: TestSpecification): Promise<TestModule> {
if (this.mode !== 'test') {
throw new Error(`The \`experimental_parseSpecification\` does not support "${this.mode}" mode.`)
}
const file = await astCollectTests(specification.project, specification.moduleId).catch((error) => {
return createFailedFileTask(specification.project, specification.moduleId, error)
})
// register in state, so it can be retrieved by "getReportedEntity"
this.state.collectFiles(specification.project, [file])
return this.state.getReportedEntity(file) as TestModule
}
/**
* Collect tests in specified modules. Vitest will run the files to collect tests.
* @param specifications A list of specifications to run.
*/
public async collectTests(specifications: TestSpecification[]): Promise<TestRunResult> {
const filepaths = specifications.map(spec => spec.moduleId)
this.state.collectPaths(filepaths)
// previous run
await this.cancelPromise
await this.runningPromise
this._onCancelListeners.clear()
this.isCancelling = false
// schedule the new run
this.runningPromise = (async () => {
if (!this.pool) {
this.pool = createPool(this)
}
const invalidates = Array.from(this.watcher.invalidates)
this.watcher.invalidates.clear()
this.snapshot.clear()
this.state.clearErrors()
await this.initializeGlobalSetup(specifications)
try {
await this.pool.collectTests(specifications, invalidates)
}
catch (err) {
this.state.catchError(err, 'Unhandled Error')
}
const files = this.state.getFiles()
// can only happen if there was a syntax error in describe block
// or there was an error importing a file
if (hasFailed(files)) {
process.exitCode = 1
}