-
-
Notifications
You must be signed in to change notification settings - Fork 1.1k
/
index.md
1161 lines (768 loc) · 34.3 KB
/
index.md
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
---
outline: deep
---
# Configuring Vitest
## Configuration
`vitest` will read your root `vite.config.ts` when it is present to match with the plugins and setup as your Vite app. If you want to have a different configuration for testing or your main app doesn't rely on Vite specifically, you could either:
- Create `vitest.config.ts`, which will have the higher priority and will override the configuration from `vite.config.ts`
- Pass `--config` option to CLI, e.g. `vitest --config ./path/to/vitest.config.ts`
- Use `process.env.VITEST` or `mode` property on `defineConfig` (will be set to `test`/`benchmark` if not overridden) to conditionally apply different configuration in `vite.config.ts`
To configure `vitest` itself, add `test` property in your Vite config. You'll also need to add a reference to Vitest types using a [triple slash command](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-) at the top of your config file, if you are importing `defineConfig` from `vite` itself.
using `defineConfig` from `vite` you should follow this:
```ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'
export default defineConfig({
test: {
// ...
},
})
```
using `defineConfig` from `vitest/config` you should follow this:
```ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
// ...
},
})
```
You can retrieve Vitest's default options to expand them if needed:
```ts
import { configDefaults, defineConfig } from 'vitest/config'
export default defineConfig({
test: {
exclude: [...configDefaults.exclude, 'packages/template/*'],
},
})
```
When using a separate `vitest.config.js`, you can also extend Vite's options from another config file if needed:
```ts
import { mergeConfig } from 'vite'
import { defineConfig } from 'vitest/config'
import viteConfig from './vite.config'
export default mergeConfig(viteConfig, defineConfig({
test: {
exclude: ['packages/template/*'],
},
}))
```
## Options
:::tip
In addition to the following options, you can also use any configuration option from [Vite](https://vitejs.dev/config/). For example, `define` to define global variables, or `resolve.alias` to define aliases.
:::
### include
- **Type:** `string[]`
- **Default:** `['**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']`
Files to include in the test run, using glob pattern.
### exclude
- **Type:** `string[]`
- **Default:** `['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**', '**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*']`
Files to exclude from the test run, using glob pattern.
### deps
- **Type:** `{ external?, inline?, ... }`
Handling for dependencies resolution.
#### deps.external
- **Type:** `(string | RegExp)[]`
- **Default:** `['**/node_modules/**', '**/dist/**']`
Externalize means that Vite will bypass the package to native Node. Externalized dependencies will not be applied Vite's transformers and resolvers, so they do not support HMR on reload. Typically, packages under `node_modules` are externalized.
#### deps.inline
- **Type:** `(string | RegExp)[] | true`
- **Default:** `[]`
Vite will process inlined modules. This could be helpful to handle packages that ship `.js` in ESM format (that Node can't handle).
If `true`, every dependency will be inlined. All dependencies, specified in [`ssr.noExternal`](https://vitejs.dev/guide/ssr.html#ssr-externals) will be inlined by default.
#### deps.fallbackCJS
- **Type** `boolean`
- **Default:** `false`
When a dependency is a valid ESM package, try to guess the cjs version based on the path. This might be helpful, if a dependency has the wrong ESM file.
This might potentially cause some misalignment if a package has different logic in ESM and CJS mode.
#### deps.registerNodeLoader
- **Type:** `boolean`
- **Default:** `false`
Use [experimental Node loader](https://nodejs.org/api/esm.html#loaders) to resolve imports inside externalized files, using Vite resolve algorithm.
If disabled, your `alias` and `<plugin>.resolveId` won't affect imports inside externalized packages (by default, `node_modules`).
#### deps.interopDefault
- **Type:** `boolean`
- **Default:** `false` if `environment` is `node`, `true` otherwise
Interpret CJS module's default as named exports. Some dependencies only bundle CJS modules and don't use named exports that Node.js can statically analyze when a package is imported using `import` syntax instead of `require`. When importing such dependencies in Node environment using named exports, you will see this error:
```
import { read } from 'fs-jetpack';
^^^^
SyntaxError: Named export 'read' not found. The requested module 'fs-jetpack' is a CommonJS module, which may not support all module.exports as named exports.
CommonJS modules can always be imported via the default export.
```
Vitest doesn't do static analysis, and cannot fail before your running code, so you will most likely see this error when running tests:
```
TypeError: createAsyncThunk is not a function
TypeError: default is not a function
```
If you are using bundlers or transpilers that bypass this Node.js limitation, you can enable this option manually. By default, Vitest assumes you are using Node ESM syntax, when `environment` is `node`, and doesn't interpret named exports.
### benchmark
- **Type:** `{ include?, exclude?, ... }`
Options used when running `vitest bench`.
### benchmark.include
- **Type:** `string[]`
- **Default:** `['**/*.{bench,benchmark}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']`
Include globs for benchmark test files
### benchmark.exclude
- **Type:** `string[]`
- **Default:** `['node_modules', 'dist', '.idea', '.git', '.cache']`
Exclude globs for benchmark test files
### benchmark.includeSource
- **Type:** `string[]`
- **Default:** `[]`
Include globs for in-source benchmark test files. This option is similar to [`includeSource`](#includesource).
When defined, Vitest will run all matched files with `import.meta.vitest` inside.
### benchmark.reporters
- **Type:** `Arrayable<BenchmarkBuiltinReporters | Reporter>`
- **Default:** `'default'`
Custom reporter for output. Can contain one or more built-in report names, reporter instances, and/or paths to custom reporters.
### benchmark.outputFile
- **Type:** `string | Record<string, string>`
Write benchmark results to a file when the `--reporter=json` option is also specified.
By providing an object instead of a string you can define individual outputs when using multiple reporters.
To provide object via CLI command, use the following syntax: `--outputFile.json=./path --outputFile.junit=./other-path`.
### alias
- **Type:** `Record<string, string> | Array<{ find: string | RegExp, replacement: string, customResolver?: ResolverFunction | ResolverObject }>`
Define custom aliases when running inside tests. They will be merged with aliases from `resolve.alias`.
### globals
- **Type:** `boolean`
- **Default:** `false`
- **CLI:** `--globals`, `--globals=false`
By default, `vitest` does not provide global APIs for explicitness. If you prefer to use the APIs globally like Jest, you can pass the `--globals` option to CLI or add `globals: true` in the config.
```ts
// vite.config.ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
globals: true,
},
})
```
To get TypeScript working with the global APIs, add `vitest/globals` to the `types` field in your `tsconfig.json`
```json
// tsconfig.json
{
"compilerOptions": {
"types": ["vitest/globals"]
}
}
```
If you are already using [`unplugin-auto-import`](https://github.com/antfu/unplugin-auto-import) in your project, you can also use it directly for auto importing those APIs.
```ts
// vite.config.ts
import { defineConfig } from 'vitest/config'
import AutoImport from 'unplugin-auto-import/vite'
export default defineConfig({
plugins: [
AutoImport({
imports: ['vitest'],
dts: true, // generate TypeScript declaration
}),
],
})
```
### environment
- **Type:** `'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string`
- **Default:** `'node'`
- **CLI:** `--environment=<env>`
The environment that will be used for testing. The default environment in Vitest
is a Node.js environment. If you are building a web application, you can use
browser-like environment through either [`jsdom`](https://github.com/jsdom/jsdom)
or [`happy-dom`](https://github.com/capricorn86/happy-dom) instead.
If you are building edge functions, you can use [`edge-runtime`](https://edge-runtime.vercel.app/packages/vm) environment
By adding a `@vitest-environment` docblock or comment at the top of the file,
you can specify another environment to be used for all tests in that file:
Docblock style:
```js
/**
* @vitest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div')
expect(element).not.toBeNull()
})
```
Comment style:
```js
// @vitest-environment happy-dom
test('use happy-dom in this test file', () => {
const element = document.createElement('div')
expect(element).not.toBeNull()
})
```
For compatibility with Jest, there is also a `@jest-environment`:
```js
/**
* @jest-environment jsdom
*/
test('use jsdom in this test file', () => {
const element = document.createElement('div')
expect(element).not.toBeNull()
})
```
If you are running Vitest with [`--threads=false`](#threads) flag, your tests will be run in this order: `node`, `jsdom`, `happy-dom`, `edge-runtime`, `custom environments`. Meaning, that every test with the same environment is grouped together, but is still running sequentially.
Starting from 0.23.0, you can also define custom environment. When non-builtin environment is used, Vitest will try to load package `vitest-environment-${name}`. That package should export an object with the shape of `Environment`:
```ts
import type { Environment } from 'vitest'
export default <Environment>{
name: 'custom',
setup() {
// custom setup
return {
teardown() {
// called after all tests with this env have been run
}
}
}
}
```
Vitest also exposes `builtinEnvironments` through `vitest/environments` entry, in case you just want to extend it. You can read more about extending environments in [our guide](/guide/environment).
### environmentOptions
- **Type:** `Record<'jsdom' | string, unknown>`
- **Default:** `{}`
These options are passed down to `setup` method of current [`environment`](#environment). By default, you can configure only JSDOM options, if you are using it as your test environment.
### update
- **Type:** `boolean`
- **Default:** `false`
- **CLI:** `-u`, `--update`, `--update=false`
Update snapshot files. This will update all changed snapshots and delete obsolete ones.
### watch
- **Type:** `boolean`
- **Default:** `true`
- **CLI:** `-w`, `--watch`, `--watch=false`
Enable watch mode
### root
- **Type:** `string`
- **CLI:** `-r <path>`, `--root=<path>`
Project root
### reporters
- **Type:** `Reporter | Reporter[]`
- **Default:** `'default'`
- **CLI:** `--reporter=<name>`, `--reporter=<name1> --reporter=<name2>`
Custom reporters for output. Reporters can be [a Reporter instance](https://github.com/vitest-dev/vitest/blob/main/packages/vitest/src/types/reporter.ts) or a string to select built in reporters:
- `'default'` - collapse suites when they pass
- `'verbose'` - keep the full task tree visible
- `'dot'` - show each task as a single dot
- `'junit'` - JUnit XML reporter (you can configure `testsuites` tag name with `VITEST_JUNIT_SUITE_NAME` environmental variable)
- `'json'` - give a simple JSON summary
- `'html'` - outputs HTML report based on [`@vitest/ui`](/guide/ui)
- path of a custom reporter (e.g. `'./path/to/reporter.ts'`, `'@scope/reporter'`)
### outputTruncateLength
- **Type:** `number`
- **Default:** `stdout.columns || 80`
- **CLI:** `--outputTruncateLength=<length>`, `--output-truncate-length=<length>`
Truncate the size of diff line up to `stdout.columns` or `80` number of characters. You may wish to tune this, depending on your terminal window width. Vitest includes `+-` characters and spaces for this. For example, you might see this diff, if you set this to `6`:
```diff
// actual line: "Text that seems correct"
- Text...
+ Test...
```
### outputDiffLines
- **Type:** `number`
- **Default:** `15`
- **CLI:** `--outputDiffLines=<lines>`, `--output-diff-lines=<lines>`
Limit the number of single output diff lines up to `15`. Vitest counts all `+-` lines when determining when to stop. For example, you might see diff like this, if you set this property to `3`:
```diff
- test: 1,
+ test: 2,
- obj: '1',
...
- test2: 1,
+ test2: 1,
- obj2: '2',
...
```
### outputDiffMaxLines
- **Type:** `number`
- **Default:** `50`
- **CLI:** `--outputDiffMaxLines=<lines>`, `--output-diff-max-lines=<lines>`
- **Version:** Since Vitest 0.26.0
The maximum number of lines to display in diff window. Beware that if you have a large object with many small diffs, you might not see all of them at once.
### outputDiffMaxSize
- **Type:** `number`
- **Default:** `10000`
- **CLI:** `--outputDiffMaxSize=<length>`, `--output-diff-max-size=<length>`
- **Version:** Since Vitest 0.26.0
The maximum length of the stringified object before the diff happens. Vitest tries to stringify an object before doing a diff, but if the object is too large, it will reduce the depth of the object to fit within this limit. Because of this, if the object is too big or nested, you might not see the diff.
Increasing this limit can increase the duration of diffing.
### outputFile
- **Type:** `string | Record<string, string>`
- **CLI:** `--outputFile=<path>`, `--outputFile.json=./path`
Write test results to a file when the `--reporter=json`, `--reporter=html` or `--reporter=junit` option is also specified.
By providing an object instead of a string you can define individual outputs when using multiple reporters.
### threads
- **Type:** `boolean`
- **Default:** `true`
- **CLI:** `--threads`, `--threads=false`
Enable multi-threading using [tinypool](https://github.com/tinylibs/tinypool) (a lightweight fork of [Piscina](https://github.com/piscinajs/piscina))
:::warning
This option is different from Jest's `--runInBand`. Vitest uses workers not only for running tests in parallel, but also to provide isolation. By disabling this option, your tests will run sequentially, but in the same global context, so you must provide isolation yourself.
This might cause all sorts of issues, if you are relying on global state (frontend frameworks usually do) or your code relies on environment to be defined separately for each test. But can be a speed boost for your tests (up to 3 times faster), that don't necessarily rely on global state or can easily bypass that.
:::
### maxThreads
- **Type:** `number`
- **Default:** _available CPUs_
Maximum number of threads. You can also use `VITEST_MAX_THREADS` environment variable.
### minThreads
- **Type:** `number`
- **Default:** _available CPUs_
Minimum number of threads. You can also use `VITEST_MIN_THREADS` environment variable.
### testTimeout
- **Type:** `number`
- **Default:** `5000`
Default timeout of a test in milliseconds
### hookTimeout
- **Type:** `number`
- **Default:** `10000`
Default timeout of a hook in milliseconds
### teardownTimeout
- **Type:** `number`
- **Default:** `1000`
Default timeout to wait for close when Vitest shuts down, in milliseconds
### silent
- **Type:** `boolean`
- **Default:** `false`
- **CLI:** `--silent`, `--silent=false`
Silent console output from tests
### setupFiles
- **Type:** `string | string[]`
Path to setup files. They will be run before each test file.
You can use `process.env.VITEST_POOL_ID` (integer-like string) inside to distinguish between threads (will always be `'1'`, if run with `threads: false`).
:::tip
Note, that if you are running [`--threads=false`](#threads), this setup file will be run in the same global scope multiple times. Meaning, that you are accessing the same global object before each test, so make sure you are not doing the same thing more than you need.
:::
For example, you may rely on a global variable:
```ts
import { config } from '@some-testing-lib'
if (!globalThis.defined) {
config.plugins = [myCoolPlugin]
computeHeavyThing()
globalThis.defined = true
}
// hooks are reset before each suite
afterEach(() => {
cleanup()
})
globalThis.resetBeforeEachTest = true
```
### globalSetup
- **Type:** `string | string[]`
Path to global setup files, relative to project root
A global setup file can either export named functions `setup` and `teardown` or a `default` function that returns a teardown function ([example](https://github.com/vitest-dev/vitest/blob/main/test/global-setup/vitest.config.ts)).
::: info
Multiple globalSetup files are possible. setup and teardown are executed sequentially with teardown in reverse order.
:::
::: warning
Beware that the global setup is run in a different global scope, so your tests don't have access to variables defined here.
:::
### watchExclude
- **Type:** `string[]`
- **Default:** `['**/node_modules/**', '**/dist/**']`
Glob pattern of file paths to be ignored from triggering watch rerun.
### forceRerunTriggers
- **Type**: `string[]`
- **Default:** `['**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**']`
Glob pattern of file paths that will trigger the whole suite rerun. When paired with the `--changed` argument will run the whole test suite if the trigger is found in the git diff.
Useful if you are testing calling CLI commands, because Vite cannot construct a module graph:
```ts
test('execute a script', async () => {
// Vitest cannot rerun this test, if content of `dist/index.js` changes
await execa('node', ['dist/index.js'])
})
```
::: tip
Make sure that your files are not excluded by `watchExclude`.
:::
### isolate
- **Type:** `boolean`
- **Default:** `true`
- **CLI:** `--isolate`, `--isolate=false`
Isolate environment for each test file. Does not work if you disable [`--threads`](#threads).
### coverage
You can use [`c8`](https://github.com/bcoe/c8) or [`istanbul`](https://istanbul.js.org/) for coverage collection.
You can provide coverage options to CLI with dot notation:
```sh
npx vitest --coverage.enabled --coverage.provider=istanbul --coverage.all
```
::: warning
If you are using coverage options with dot notation, don't forget to specify `--coverage.enabled`. Do not provide a single `--coverage` option in that case.
:::
#### provider
- **Type:** `'c8' | 'istanbul'`
- **Default:** `'c8'`
- **CLI:** `--coverage.provider=<provider>`
Use `provider` to select the tool for coverage collection.
#### enabled
- **Type:** `boolean`
- **Default:** `false`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.enabled`, `--coverage.enabled=false`
Enables coverage collection. Can be overriden using `--coverage` CLI option.
#### include
- **Type:** `string[]`
- **Default:** `['**']`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.include=<path>`, `--coverage.include=<path1> --coverage.include=<path2>`
List of files included in coverage as glob patterns
#### extension
- **Type:** `string | string[]`
- **Default:** `['.js', '.cjs', '.mjs', '.ts', '.mts', '.cts', '.tsx', '.jsx', '.vue', '.svelte']`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.extension=<extension>`, `--coverage.extension=<extension1> --coverage.extension=<extension2>`
#### exclude
- **Type:** `string[]`
- **Default:**
```js
[
'coverage/**',
'dist/**',
'packages/*/test{,s}/**',
'**/*.d.ts',
'cypress/**',
'test{,s}/**',
'test{,-*}.{js,cjs,mjs,ts,tsx,jsx}',
'**/*{.,-}test.{js,cjs,mjs,ts,tsx,jsx}',
'**/*{.,-}spec.{js,cjs,mjs,ts,tsx,jsx}',
'**/__tests__/**',
'**/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress}.config.*',
'**/.{eslint,mocha,prettier}rc.{js,cjs,yml}',
]
```
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.exclude=<path>`, `--coverage.exclude=<path1> --coverage.exclude=<path2>`
List of files excluded from coverage as glob patterns.
#### all
- **Type:** `boolean`
- **Default:** `false`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.all`, --coverage.all=false`
Whether to include all files, including the untested ones into report.
#### clean
- **Type:** `boolean`
- **Default:** `true`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.clean`, `--coverage.clean=false`
Clean coverage results before running tests
#### cleanOnRerun
- **Type:** `boolean`
- **Default:** `true`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.cleanOnRerun`, `--coverage.cleanOnRerun=false`
Clean coverage report on watch rerun
#### reportsDirectory
- **Type:** `string`
- **Default:** `'./coverage'`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.reportsDirectory=<path>`
Directory to write coverage report to.
When using `c8` provider a temporary `/tmp` directory is created for [V8 coverage results](https://nodejs.org/api/cli.html#coverage-output).
#### reporter
- **Type:** `string | string[]`
- **Default:** `['text', 'html', 'clover', 'json']`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.reporter=<reporter>`, `--coverage.reporter=<reporter1> --coverage.reporter=<reporter2>`
Coverage reporters to use. See [istanbul documentation](https://istanbul.js.org/docs/advanced/alternative-reporters/) for detailed list of all reporters.
#### skipFull
- **Type:** `boolean`
- **Default:** `false`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.skipFull`, `--coverage.skipFull=false`
Do not show files with 100% statement, branch, and function coverage.
#### perFile
- **Type:** `boolean`
- **Default:** `false`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.perFile`, `--coverage.perFile=false`
Check thresholds per file.
See `lines`, `functions`, `branches` and `statements` for the actual thresholds.
#### lines
- **Type:** `number`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.lines=<number>`
Threshold for lines.
See [istanbul documentation](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information.
#### functions
- **Type:** `number`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.functions=<number>`
Threshold for functions.
See [istanbul documentation](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information.
#### branches
- **Type:** `number`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.branches=<number>`
Threshold for branches.
See [istanbul documentation](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information.
#### statements
- **Type:** `number`
- **Available for providers:** `'c8' | 'istanbul'`
- **CLI:** `--coverage.statements=<number>`
Threshold for statements.
See [istanbul documentation](https://github.com/istanbuljs/nyc#coverage-thresholds) for more information.
#### allowExternal
- **Type:** `boolean`
- **Default:** `false`
- **Available for providers:** `'c8'`
- **CLI:** `--coverage.allowExternal`, `--coverage.allowExternal=false`
Allow files from outside of your cwd.
#### excludeNodeModules
- **Type:** `boolean`
- **Default:** `true`
- **Available for providers:** `'c8'`
- **CLI:** `--coverage.excludeNodeModules`, `--coverage.excludeNodeModules=false`
Exclude coverage under `/node_modules/`.
#### src
- **Type:** `string[]`
- **Default:** `process.cwd()`
- **Available for providers:** `'c8'`
- **CLI:** `--coverage.src=<path>`
Specifies the directories that are used when `--all` is enabled.
#### 100
- **Type:** `boolean`
- **Default:** `false`
- **Available for providers:** `'c8'`
- **CLI:** `--coverage.100`, `--coverage.100=false`
Shortcut for `--check-coverage --lines 100 --functions 100 --branches 100 --statements 100`.
#### ignoreClassMethods
- **Type:** `string[]`
- **Default:** `[]`
- **Available for providers:** `'istanbul'`
- **CLI:** `--coverage.ignoreClassMethods=<method>`
Set to array of class method names to ignore for coverage.
See [istanbul documentation](https://github.com/istanbuljs/nyc#ignoring-methods) for more information.
#### watermarks
- **Type:**
<!-- eslint-skip -->
```ts
{
statements?: [number, number],
functions?: [number, number],
branches?: [number, number],
lines?: [number, number]
}
```
- **Default:**
<!-- eslint-skip -->
```ts
{
statements: [50, 80],
functions: [50, 80],
branches: [50, 80],
lines: [50, 80]
}
```
- **Available for providers:** `'istanbul'`
Watermarks for statements, lines, branches and functions. See [istanbul documentation](https://github.com/istanbuljs/nyc#high-and-low-watermarks) for more information.
### testNamePattern
- **Type** `string | RegExp`
- **CLI:** `-t <pattern>`, `--testNamePattern=<pattern>`, `--test-name-pattern=<pattern>`
Run tests with full names matching the pattern.
If you add `OnlyRunThis` to this property, tests not containing the word `OnlyRunThis` in the test name will be skipped.
```js
import { expect, test } from 'vitest'
// run
test('OnlyRunThis', () => {
expect(true).toBe(true)
})
// skipped
test('doNotRun', () => {
expect(true).toBe(true)
})
```
### open
- **Type:** `boolean`
- **Default:** `false`
- **CLI:** `--open`, `--open=false`
Open Vitest UI (WIP)
### api
- **Type:** `boolean | number`
- **Default:** `false`
- **CLI:** `--api`, `--api.port`, `--api.host`, `--api.strictPort`
Listen to port and serve API. When set to true, the default port is 51204
### clearMocks
- **Type:** `boolean`
- **Default:** `false`
Will call [`.mockClear()`](/api/#mockclear) on all spies before each test. This will clear mock history, but not reset its implementation to the default one.
### mockReset
- **Type:** `boolean`
- **Default:** `false`
Will call [`.mockReset()`](/api/#mockreset) on all spies before each test. This will clear mock history and reset its implementation to an empty function (will return `undefined`).
### restoreMocks
- **Type:** `boolean`
- **Default:** `false`
Will call [`.mockRestore()`](/api/#mockrestore) on all spies before each test. This will clear mock history and reset its implementation to the original one.
### unstubEnvs
- **Type:** `boolean`
- **Default:** `false`
- **Version:** Since Vitest 0.26.0
Will call [`vi.unstubAllEnvs`](/api/#vi-unstuballenvs) before each test.
### unstubGlobals
- **Type:** `boolean`
- **Default:** `false`
- **Version:** Since Vitest 0.26.0
Will call [`vi.unstubAllGlobals`](/api/#vi-unstuballglobals) before each test.
### transformMode
- **Type:** `{ web?, ssr? }`
Determine the transform method of modules
#### transformMode.ssr
- **Type:** `RegExp[]`
- **Default:** `[/\.([cm]?[jt]sx?|json)$/]`
Use SSR transform pipeline for the specified files.<br>
Vite plugins will receive `ssr: true` flag when processing those files.
#### transformMode.web
- **Type:** `RegExp[]`
- **Default:** *modules other than those specified in `transformMode.ssr`*
First do a normal transform pipeline (targeting browser), then do a SSR rewrite to run the code in Node.<br>
Vite plugins will receive `ssr: false` flag when processing those files.
When you use JSX as component models other than React (e.g. Vue JSX or SolidJS), you might want to config as following to make `.tsx` / `.jsx` transformed as client-side components:
```ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
transformMode: {
web: [/\.[jt]sx$/],
},
},
})
```
### snapshotFormat
- **Type:** `PrettyFormatOptions`
Format options for snapshot testing. These options are passed down to [`pretty-format`](https://www.npmjs.com/package/pretty-format).
### resolveSnapshotPath
- **Type**: `(testPath: string, snapExtension: string) => string`
- **Default**: stores snapshot files in `__snapshots__` directory
Overrides default snapshot path. For example, to store snapshots next to test files:
```ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
resolveSnapshotPath: (testPath, snapExtension) => testPath + snapExtension,
},
})
```
### allowOnly
- **Type**: `boolean`
- **Default**: `false`
- **CLI:** `--allowOnly`, `--allowOnly=false`
Allow tests and suites that are marked as only.
### dangerouslyIgnoreUnhandledErrors
- **Type**: `boolean`
- **Default**: `false`
- **CLI:** `--dangerouslyIgnoreUnhandledErrors` `--dangerouslyIgnoreUnhandledErrors=false`
Ignore any unhandled errors that occur.
### passWithNoTests
- **Type**: `boolean`
- **Default**: `false`
- **CLI:** `--passWithNoTests`, `--passWithNoTests=false`
Vitest will not fail, if no tests will be found.
### logHeapUsage
- **Type**: `boolean`
- **Default**: `false`
- **CLI:** `--logHeapUsage`, `--logHeapUsage=false`
Show heap usage after each test. Useful for debugging memory leaks.
### css
- **Type**: `boolean | { include?, exclude?, modules? }`
Configure if CSS should be processed. When excluded, CSS files will be replaced with empty strings to bypass the subsequent processing. CSS Modules will return a proxy to not affect runtime.
#### css.include
- **Type**: `RegExp | RegExp[]`
- **Default**: `[]`
RegExp pattern for files that should return actual CSS and will be processed by Vite pipeline.
:::tip
To process all CSS files, use `/.+/`.
:::