New Topic2222 a224
Getting Starteds1
Overview
Vitest is a next generation testing framework powered by Vite.
Vitest is a next generation testing framework powered by Vite.
33You can learn more about the rationale behind the project in the Why Vitest section.fggffggf333Star
t Vitest in the current directory. Will enter the watch mode in development environment and run mode in CI automatically.
Trying Vitest Online
You can try Vitest online on StackBlitz. It runs Vitest directly in the browser, and it is almost identical to the local setup but doesn't require installing anything on your machine.
Adding Vitest to Your Project
npmyarnpnpmbun
bash
npm install -D vitestTIP
Vitest 1.0 requires Vite >=v5.0.0 and Node >=v18.0.0
It is recommended that you install a copy of vitest in your package.json, using one of the methods listed above. However, if you would prefer to run vitest directly, you can use npx vitest (the npx command comes with npm and Node.js).
The npx command will execute the command either from a local node_modules/.bin installing any packages needed in order for the command to run. By default, npx will check whether command exists in $PATH, or in the local project binaries, and execute that. If command is not found, it will be installed prior to execution.
Writing Tests
As an example, we will write a simple test that verifies the output of a function that adds two numbers.
js
// sum.js
export function sum(a, b) {
return a + b
}js
// sum.test.js
import { expect, test } from 'vitest'
import { sum } from './sum'
test('adds 1 + 2 to equal 3', () => {
expect(sum(1, 2)).toBe(3)
})TIP
By default, tests must contain ".test." or ".spec." in their file name.
Next, in order to execute the test, add the following section to your package.json:
json
{
"scripts": {
"test": "vitest"
}
}Finally, run npm run test, yarn test, or pnpm test, depending on your package manager, and Vitest will print this message:
txt
✓ sum.test.js (1)
✓ adds 1 + 2 to equal 3
Test Files 1 passed (1)
Tests 1 passed (1)
Start at 02:15:44
Duration 311msLearn more about the usage of Vitest, see the API section.
Configuring Vitest
One of the main advantages of Vitest is its unified configuration with Vite. If present, vitest will read your root vite.config.ts to match with the plugins and setup as your Vite app. For example, your Vite resolve.alias and plugins configuration will work out-of-the-box. If you want a different configuration during testing, you can:
- Create
vitest.config.ts, which will have the higher priority - Pass
--configoption to CLI, e.g.vitest --config ./path/to/vitest.config.ts - Use
process.env.VITESTormodeproperty ondefineConfig(will be set totestif not overridden) to conditionally apply different configuration invite.config.ts
Vitest supports the same extensions for your configuration file as Vite does: .js, .mjs, .cjs, .ts, .cts, .mts. Vitest does not support .json extension.
If you are not using Vite as your build tool, you can configure Vitest using the test property in your config file:
ts
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
// ...
},
})TIP
Even if you do not use Vite yourself, Vitest relies heavily on it for its transformation pipeline. For that reason, you can also configure any property described in Vite documentation.
If you are already using Vite, add test property in your Vite config. You'll also need to add a reference to Vitest types using a triple slash directive at the top of your config file.
ts
/// <reference types="vitest" />
import { defineConfig } from 'vite'
export default defineConfig({
test: {
// ...
},
})See the list of config options in the Config Reference
WARNING
If you decide to have two separate config files for Vite and Vitest, make sure to define the same Vite options in your Vitest config file since it will override your Vite file, not extend it. You can also use mergeConfig method from vite or vitest/config entries to merge Vite config with Vitest config:
vitest.config.mjsvite.config.mjs
ts
import { defineConfig, mergeConfig } from 'vitest/config'
import viteConfig from './vite.config.mjs'
export default mergeConfig(viteConfig, defineConfig({
test: {
// ...
}
}))But we recommend to use the same file for both Vite and Vitest instead of creating two separate files.
Workspaces Support
Run different project configurations inside the same project with Vitest Workspaces. You can define a list of files and folders that define your workspace in vitest.workspace file. The file supports js/ts/json extensions. This feature works great with monorepo setups.
ts
import { defineWorkspace } from 'vitest/config'
export default defineWorkspace([
// you can use a list of glob patterns to define your workspaces
// Vitest expects a list of config files
// or directories where there is a config file
'packages/*',
'tests/*/vitest.config.{e2e,unit}.ts',
// you can even run the same tests,
// but with different configs in the same "vitest" process
{
test: {
name: 'happy-dom',
root: './shared_tests',
environment: 'happy-dom',
setupFiles: ['./setup.happy-dom.ts'],
},
},
{
test: {
name: 'node',
root: './shared_tests',
environment: 'node',
setupFiles: ['./setup.node.ts'],
},
},
])Command Line Interface
In a project where Vitest is installed, you can use the vitest binary in your npm scripts, or run it directly with npx vitest. Here are the default npm scripts in a scaffolded Vitest project:
json
{
"scripts": {
"test": "vitest",
"coverage": "vitest run --coverage"
}
}To run tests once without watching for file changes, use vitest run. You can specify additional CLI options like --port or --https. For a full list of CLI options, run npx vitest --help in your project.
Learn more about the Command Line Interface
IDE Integrations
We also provided a official extension for Visual Studio Code to enhance your testing experience with Vitest.
Install from VS Code Marketplace
Learn more about IDE Integrations
Examples
| Example | Source | Playground |
|---|---|---|
basic | GitHub | Play Online |
fastify | GitHub | Play Online |
lit | GitHub | Play Online |
marko | GitHub | Play Online |
preact | GitHub | Play Online |
react | GitHub | Play Online |
solid | GitHub | Play Online |
sveltekit | GitHub | Play Online |
typecheck | GitHub | Play Online |
workspace | GitHub | Play Online |
Projects using Vitest
- unocss
- unplugin-auto-import
- unplugin-vue-components
- vue
- vite
- vitesse
- vitesse-lite
- fluent-vue
- vueuse
- milkdown
- gridjs-svelte
- spring-easing
- bytemd
- faker
- million
- Vitamin
- neodrag
- svelte-multiselect
- iconify
- tdesign-vue-next
- cz-git
Using Unreleased Commits
If you can't wait for a new release to test the latest features, you will need to clone the vitest repo to your local machine and then build and link it yourself (pnpm is required):
bash
git clone https://github.com/vitest-dev/vitest.git
cd vitest
pnpm install
cd packages/vitest
pnpm run build
pnpm link --global # you can use your preferred package manager for this stepThen go to the project where you are using Vitest and run pnpm link --global vitest (or the package manager that you used to link vitest globally).
Community
If you have questions or need help, reach out to the community at Discord and GitHub Discussions.
Workspace
Sample Project
Vitest provides built-in support for monorepos through a workspace configuration file. You can create a workspace to define your project's setups.
Defining a Workspace
A workspace should have a vitest.workspace or vitest.projects file in its root (in the same folder as your config file if you have one). Vitest supports ts/js/json extensions for this file.
Workspace configuration file should have a default export with a list of files or glob patterns referencing your projects. For example, if you have a folder named packages that contains your projects, you can define a workspace with this config file:
vitest.workspace.ts
ts
export default [
'packages/*'
]Vitest will consider every folder in packages as a separate project even if it doesn't have a config file inside.
WARNING
Vitest will not consider the root config as a workspace project (so it will not run tests specified in include) unless it is specified in this config.
You can also reference projects with their config files:
vitest.workspace.ts
ts
export default [
'packages/*/vitest.config.{e2e,unit}.ts'
]This pattern will only include projects with vitest.config file that includes e2e and unit before the extension.
WARNING
If you are referencing filenames with glob pattern, make sure your config file starts with vite.config or vitest.config. Otherwise Vitest will skip it.
You can also define projects with inline config. Workspace file supports using both syntaxes at the same time.
vitest.workspace.ts
ts
import { defineWorkspace } from 'vitest/config'
// defineWorkspace provides a nice type hinting DX
export default defineWorkspace([
'packages/*',
{
// add "extends" to merge two configs together
extends: './vite.config.js',
test: {
include: ['tests/**/*.{browser}.test.{ts,js}'],
// it is recommended to define a name when using inline configs
name: 'happy-dom',
environment: 'happy-dom',
}
},
{
test: {
include: ['tests/**/*.{node}.test.{ts,js}'],
name: 'node',
environment: 'node',
}
}
])WARNING
All projects should have unique names. Otherwise, Vitest will throw an error. If you do not provide a name inside the inline config, Vitest will assign a number. If you don't provide a name inside a project config defined with glob syntax, Vitest will use the directory name by default.
If you don't rely on inline configs, you can just create a small json file in your root directory:
vitest.workspace.json
json
[
"packages/*"
]Workspace projects don't support all configuration properties. For better type safety, use defineProject instead of defineConfig method inside project configuration files:
packages/a/vitest.config.ts
ts
import { defineProject } from 'vitest/config'
export default defineProject({
test: {
environment: 'jsdom',
// "reporters" is not supported in a project config,
// so it will show an error
reporters: ['json']No overload matches this call.
The last overload gave the following error.
Object literal may only specify known properties, and 'reporters' does not exist in type 'ProjectConfig'. }
})Running tests
To run tests inside the workspace, define a script in your root package.json:
json
{
"scripts": {
"test": "vitest"
}
}Now tests can be run using your package manager:
npmyarnpnpmbun
bash
npm run testIf you need to run tests only inside a single project, use the --project CLI option:
bash
npm run test --project e2eTIP
CLI option --project can be used multiple times to filter out several projects:
bash
npm run test --project e2e --project unitConfiguration
None of the configuration options are inherited from the root-level config file. You can create a shared config file and merge it with the project config yourself:
packages/a/vitest.config.ts
ts
import { defineProject, mergeConfig } from 'vitest/config'
import configShared from '../vitest.shared.js'
export default mergeConfig(
configShared,
defineProject({
test: {
environment: 'jsdom',
}
})
)At the defineWorkspace level you can also use the extends option instead to inherit from your root-level config.
packages/a/vitest.config.ts
ts
import { defineWorkspace } from 'vitest/config'
export default defineWorkspace([
{
extends: './vitest.config.ts',
test: {
name: 'unit',
include: ['**/*.unit.test.ts'],
},
},
{
extends: './vitest.config.ts',
test: {
name: 'integration',
include: ['**/*.integration.test.ts'],
},
},
])Also, some of the configuration options are not allowed in a project config. Most notably:
coverage: coverage is done for the whole workspacereporters: only root-level reporters can be supportedresolveSnapshotPath: only root-level resolver is respected- all other options that don't affect test runners
TIP
All configuration options that are not supported inside a project config have * sign next them in "Config" page.
Coverage
Coverage for workspace projects works out of the box. But if you have all option enabled and use non-conventional extensions in some of your projects, you will need to have a plugin that handles this extension in your root configuration file.
For example, if you have a package that uses Vue files and it has its own config file, but some of the files are not imported in your tests, coverage will fail trying to analyze the usage of unused files, because it relies on the root configuration rather than project configuration.
Command Line Interface
Commands
vitest
Start Vitest in the current directory. Will enter the watch mode in development environment and run mode in CI automatically.
You can pass an additional argument as the filter of the test files to run. For example:
bash
vitest foobarWill run only the test file that contains foobar in their paths. This filter only checks inclusion and doesn't support regexp or glob patterns (unless your terminal processes it before Vitest receives the filter).
vitest run
Perform a single run without watch mode.
vitest watch
Run all test suites but watch for changes and rerun tests when they change. Same as calling vitest without an argument. Will fallback to vitest run in CI.
vitest dev
Alias to vitest watch.
vitest related
Run only tests that cover a list of source files. Works with static imports (e.g., import('./index.js') or import index from './index.js), but not the dynamic ones (e.g., import(filepath)). All files should be relative to root folder.
Useful to run with lint-staged or with your CI setup.
bash
vitest related /src/index.ts /src/hello-world.jsTIP
Don't forget that Vitest runs with enabled watch mode by default. If you are using tools like lint-staged, you should also pass --run option, so that command can exit normally.
js
// .lintstagedrc.js
export default {
'*.{js,ts}': 'vitest related --run',
}vitest bench
Run only benchmark tests, which compare performance results.
vitest init
vitest init <name> can be used to setup project configuration. At the moment, it only supports browser value:
bash
vitest init browservitest list
vitest list command inherits all vitest options to print the list of all matching tests. This command ignores reporters option. By default, it will print the names of all tests that matched the file filter and name pattern:
shell
vitest list filename.spec.ts -t="some-test"txt
describe > some-test
describe > some-test > test 1
describe > some-test > test 2You can pass down --json flag to print tests in JSON format or save it in a separate file:
bash
vitest list filename.spec.ts -t="some-test" --json=./file.jsonIf --json flag doesn't receive a value, it will output the JSON into stdout.
Options
TIP
Vitest supports both camel case and kebab case for CLI arguments. For example, --passWithNoTests and --pass-with-no-tests will both work (--no-color and --inspect-brk are the exceptions).
Vitest also supports different ways of specifying the value: --reporter dot and --reporter=dot are both valid.
If option supports an array of values, you need to pass the option multiple times:
vitest --reporter=dot --reporter=defaultBoolean options can be negated with no- prefix. Specifying the value as false also works:
vitest --no-api
vitest --api=falseroot
- CLI:
-r, --root <path> - Config: root
Root path
config
- CLI:
-c, --config <path>
Path to config file
update
- CLI:
-u, --update - Config: update
Update snapshot
watch
- CLI:
-w, --watch - Config: watch
Enable watch mode
testNamePattern
- CLI:
-t, --testNamePattern <pattern> - Config: testNamePattern
Run tests with full names matching the specified regexp pattern
dir
- CLI:
--dir <path> - Config: dir
Base directory to scan for the test files
ui
- CLI:
--ui - Config: ui
Enable UI
open
- CLI:
--open - Config: open
Open UI automatically (default: !process.env.CI)
api.port
- CLI:
--api.port [port]
Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. If true will be set to 51204
api.host
- CLI:
--api.host [host]
Specify which IP addresses the server should listen on. Set this to 0.0.0.0 or true to listen on all addresses, including LAN and public addresses
api.strictPort
- CLI:
--api.strictPort
Set to true to exit if port is already in use, instead of automatically trying the next available port
silent
- CLI:
--silent - Config: silent
Silent console output from tests
hideSkippedTests
- CLI:
--hideSkippedTests
Hide logs for skipped tests
reporters
- CLI:
--reporter <name> - Config: reporters
Specify reporters
outputFile
- CLI:
--outputFile <filename/-s> - Config: outputFile
Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters (example: --outputFile.tap=./tap.txt)
coverage.all
- CLI:
--coverage.all - Config: coverage.all
Whether to include all files, including the untested ones into report
coverage.provider
- CLI:
--coverage.provider <name> - Config: coverage.provider
Select the tool for coverage collection, available values are: "v8", "istanbul" and "custom"
coverage.enabled
- CLI:
--coverage.enabled - Config: coverage.enabled
Enables coverage collection. Can be overridden using the --coverage CLI option (default: false)
coverage.include
- CLI:
--coverage.include <pattern> - Config: coverage.include
Files included in coverage as glob patterns. May be specified more than once when using multiple patterns (default: **)
coverage.exclude
- CLI:
--coverage.exclude <pattern> - Config: coverage.exclude
Files to be excluded in coverage. May be specified more than once when using multiple extensions (default: Visit coverage.exclude)
coverage.extension
- CLI:
--coverage.extension <extension> - Config: coverage.extension
Extension to be included in coverage. May be specified more than once when using multiple extensions (default: [".js", ".cjs", ".mjs", ".ts", ".mts", ".tsx", ".jsx", ".vue", ".svelte"])
coverage.clean
- CLI:
--coverage.clean - Config: coverage.clean
Clean coverage results before running tests (default: true)
coverage.cleanOnRerun
- CLI:
--coverage.cleanOnRerun - Config: coverage.cleanOnRerun
Clean coverage report on watch rerun (default: true)
coverage.reportsDirectory
- CLI:
--coverage.reportsDirectory <path> - Config: coverage.reportsDirectory
Directory to write coverage report to (default: ./coverage)
coverage.reporter
- CLI:
--coverage.reporter <name> - Config: coverage.reporter
Coverage reporters to use. Visit coverage.reporter for more information (default: ["text", "html", "clover", "json"])
coverage.reportOnFailure
- CLI:
--coverage.reportOnFailure - Config: coverage.reportOnFailure
Generate coverage report even when tests fail (default: false)
coverage.allowExternal
- CLI:
--coverage.allowExternal - Config: coverage.allowExternal
Collect coverage of files outside the project root (default: false)
coverage.skipFull
- CLI:
--coverage.skipFull - Config: coverage.skipFull
Do not show files with 100% statement, branch, and function coverage (default: false)
coverage.thresholds.100
- CLI:
--coverage.thresholds.100 - Config: coverage.thresholds.100
Shortcut to set all coverage thresholds to 100 (default: false)
coverage.thresholds.perFile
- CLI:
--coverage.thresholds.perFile - Config: coverage.thresholds.perFile
Check thresholds per file. See --coverage.thresholds.lines, --coverage.thresholds.functions, --coverage.thresholds.branches and --coverage.thresholds.statements for the actual thresholds (default: false)
coverage.thresholds.autoUpdate
- CLI:
--coverage.thresholds.autoUpdate - Config: coverage.thresholds.autoUpdate
Update threshold values: "lines", "functions", "branches" and "statements" to configuration file when current coverage is above the configured thresholds (default: false)
coverage.thresholds.lines
- CLI:
--coverage.thresholds.lines <number>
Threshold for lines. Visit istanbuljs for more information. This option is not available for custom providers
coverage.thresholds.functions
- CLI:
--coverage.thresholds.functions <number>
Threshold for functions. Visit istanbuljs for more information. This option is not available for custom providers
coverage.thresholds.branches
- CLI:
--coverage.thresholds.branches <number>
Threshold for branches. Visit istanbuljs for more information. This option is not available for custom providers
coverage.thresholds.statements
- CLI:
--coverage.thresholds.statements <number>
Threshold for statements. Visit istanbuljs for more information. This option is not available for custom providers
coverage.ignoreClassMethods
- CLI:
--coverage.ignoreClassMethods <name> - Config: coverage.ignoreClassMethods
Array of class method names to ignore for coverage. Visit istanbuljs for more information. This option is only available for the istanbul providers (default: [])
coverage.processingConcurrency
- CLI:
--coverage.processingConcurrency <number> - Config: coverage.processingConcurrency
Concurrency limit used when processing the coverage results. (default min between 20 and the number of CPUs)
coverage.customProviderModule
- CLI:
--coverage.customProviderModule <path> - Config: coverage.customProviderModule
Specifies the module name or path for the custom coverage provider module. Visit Custom Coverage Provider for more information. This option is only available for custom providers
coverage.watermarks.statements
- CLI:
--coverage.watermarks.statements <watermarks>
High and low watermarks for statements in the format of <high>,<low>
coverage.watermarks.lines
- CLI:
--coverage.watermarks.lines <watermarks>
High and low watermarks for lines in the format of <high>,<low>
coverage.watermarks.branches
- CLI:
--coverage.watermarks.branches <watermarks>
High and low watermarks for branches in the format of <high>,<low>
coverage.watermarks.functions
- CLI:
--coverage.watermarks.functions <watermarks>
High and low watermarks for functions in the format of <high>,<low>
mode
- CLI:
--mode <name> - Config: mode
Override Vite mode (default: test or benchmark)
workspace
- CLI:
--workspace <path> - Config: workspace
Path to a workspace configuration file
isolate
- CLI:
--isolate - Config: isolate
Run every test file in isolation. To disable isolation, use --no-isolate (default: true)
globals
- CLI:
--globals - Config: globals
Inject apis globally
dom
- CLI:
--dom
Mock browser API with happy-dom
browser.enabled
- CLI:
--browser.enabled - Config: browser.enabled
Run tests in the browser. Equivalent to --browser.enabled (default: false)
browser.name
- CLI:
--browser.name <name> - Config: browser.name
Run all tests in a specific browser. Some browsers are only available for specific providers (see --browser.provider). Visit browser.name for more information
browser.headless
- CLI:
--browser.headless - Config: browser.headless
Run the browser in headless mode (i.e. without opening the GUI (Graphical User Interface)). If you are running Vitest in CI, it will be enabled by default (default: process.env.CI)
browser.api.port
- CLI:
--browser.api.port [port] - Config: browser.api.port
Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. If true will be set to 63315
browser.api.host
- CLI:
--browser.api.host [host] - Config: browser.api.host
Specify which IP addresses the server should listen on. Set this to 0.0.0.0 or true to listen on all addresses, including LAN and public addresses
browser.api.strictPort
- CLI:
--browser.api.strictPort - Config: browser.api.strictPort
Set to true to exit if port is already in use, instead of automatically trying the next available port
browser.provider
- CLI:
--browser.provider <name> - Config: browser.provider
Provider used to run browser tests. Some browsers are only available for specific providers. Can be "webdriverio", "playwright", "preview", or the path to a custom provider. Visit browser.provider for more information (default: "preview")
browser.providerOptions
- CLI:
--browser.providerOptions <options> - Config: browser.providerOptions
Options that are passed down to a browser provider. Visit browser.providerOptions for more information
browser.isolate
- CLI:
--browser.isolate - Config: browser.isolate
Run every browser test file in isolation. To disable isolation, use --browser.isolate=false (default: true)
browser.ui
- CLI:
--browser.ui - Config: browser.ui
Show Vitest UI when running tests (default: !process.env.CI)
browser.fileParallelism
- CLI:
--browser.fileParallelism - Config: browser.fileParallelism
Should browser test files run in parallel. Use --browser.fileParallelism=false to disable (default: true)
pool
- CLI:
--pool <pool> - Config: pool
Specify pool, if not running in the browser (default: threads)
poolOptions.threads.isolate
- CLI:
--poolOptions.threads.isolate - Config: poolOptions.threads.isolate
Isolate tests in threads pool (default: true)
poolOptions.threads.singleThread
- CLI:
--poolOptions.threads.singleThread - Config: poolOptions.threads.singleThread
Run tests inside a single thread (default: false)
poolOptions.threads.maxThreads
- CLI:
--poolOptions.threads.maxThreads <workers> - Config: poolOptions.threads.maxThreads
Maximum number or percentage of threads to run tests in
poolOptions.threads.minThreads
- CLI:
--poolOptions.threads.minThreads <workers> - Config: poolOptions.threads.minThreads
Minimum number or percentage of threads to run tests in
poolOptions.threads.useAtomics
- CLI:
--poolOptions.threads.useAtomics - Config: poolOptions.threads.useAtomics
Use Atomics to synchronize threads. This can improve performance in some cases, but might cause segfault in older Node versions (default: false)
poolOptions.vmThreads.isolate
- CLI:
--poolOptions.vmThreads.isolate - Config: poolOptions.vmThreads.isolate
Isolate tests in threads pool (default: true)
poolOptions.vmThreads.singleThread
- CLI:
--poolOptions.vmThreads.singleThread - Config: poolOptions.vmThreads.singleThread
Run tests inside a single thread (default: false)
poolOptions.vmThreads.maxThreads
- CLI:
--poolOptions.vmThreads.maxThreads <workers> - Config: poolOptions.vmThreads.maxThreads
Maximum number or percentage of threads to run tests in
poolOptions.vmThreads.minThreads
- CLI:
--poolOptions.vmThreads.minThreads <workers> - Config: poolOptions.vmThreads.minThreads
Minimum number or percentage of threads to run tests in
poolOptions.vmThreads.useAtomics
- CLI:
--poolOptions.vmThreads.useAtomics - Config: poolOptions.vmThreads.useAtomics
Use Atomics to synchronize threads. This can improve performance in some cases, but might cause segfault in older Node versions (default: false)
poolOptions.vmThreads.memoryLimit
- CLI:
--poolOptions.vmThreads.memoryLimit <limit> - Config: poolOptions.vmThreads.memoryLimit
Memory limit for VM threads pool. If you see memory leaks, try to tinker this value.
poolOptions.forks.isolate
- CLI:
--poolOptions.forks.isolate - Config: poolOptions.forks.isolate
Isolate tests in forks pool (default: true)
poolOptions.forks.singleFork
- CLI:
--poolOptions.forks.singleFork - Config: poolOptions.forks.singleFork
Run tests inside a single child_process (default: false)
poolOptions.forks.maxForks
- CLI:
--poolOptions.forks.maxForks <workers> - Config: poolOptions.forks.maxForks
Maximum number or percentage of processes to run tests in
poolOptions.forks.minForks
- CLI:
--poolOptions.forks.minForks <workers> - Config: poolOptions.forks.minForks
Minimum number or percentage of processes to run tests in
poolOptions.vmForks.isolate
- CLI:
--poolOptions.vmForks.isolate - Config: poolOptions.vmForks.isolate
Isolate tests in forks pool (default: true)
poolOptions.vmForks.singleFork
- CLI:
--poolOptions.vmForks.singleFork - Config: poolOptions.vmForks.singleFork
Run tests inside a single child_process (default: false)
poolOptions.vmForks.maxForks
- CLI:
--poolOptions.vmForks.maxForks <workers> - Config: poolOptions.vmForks.maxForks
Maximum number or percentage of processes to run tests in
poolOptions.vmForks.minForks
- CLI:
--poolOptions.vmForks.minForks <workers> - Config: poolOptions.vmForks.minForks
Minimum number or percentage of processes to run tests in
poolOptions.vmForks.memoryLimit
- CLI:
--poolOptions.vmForks.memoryLimit <limit> - Config: poolOptions.vmForks.memoryLimit
Memory limit for VM forks pool. If you see memory leaks, try to tinker this value.
fileParallelism
- CLI:
--fileParallelism - Config: fileParallelism
Should all test files run in parallel. Use --no-file-parallelism to disable (default: true)
maxWorkers
- CLI:
--maxWorkers <workers> - Config: maxWorkers
Maximum number or percentage of workers to run tests in
minWorkers
- CLI:
--minWorkers <workers> - Config: minWorkers
Minimum number or percentage of workers to run tests in
environment
- CLI:
--environment <name> - Config: environment
Specify runner environment, if not running in the browser (default: node)
passWithNoTests
- CLI:
--passWithNoTests - Config: passWithNoTests
Pass when no tests are found
logHeapUsage
- CLI:
--logHeapUsage - Config: logHeapUsage
Show the size of heap for each test when running in node
allowOnly
- CLI:
--allowOnly - Config: allowOnly
Allow tests and suites that are marked as only (default: !process.env.CI)
dangerouslyIgnoreUnhandledErrors
- CLI:
--dangerouslyIgnoreUnhandledErrors - Config: dangerouslyIgnoreUnhandledErrors
Ignore any unhandled errors that occur
sequence.shuffle.files
- CLI:
--sequence.shuffle.files - Config: sequence.shuffle.files
Run files in a random order. Long running tests will not start earlier if you enable this option. (default: false)
sequence.shuffle.tests
- CLI:
--sequence.shuffle.tests - Config: sequence.shuffle.tests
Run tests in a random order (default: false)
sequence.concurrent
- CLI:
--sequence.concurrent - Config: sequence.concurrent
Make tests run in parallel (default: false)
sequence.seed
- CLI:
--sequence.seed <seed> - Config: sequence.seed
Set the randomization seed. This option will have no effect if --sequence.shuffle is falsy. Visit "Random Seed" page for more information
sequence.hooks
- CLI:
--sequence.hooks <order> - Config: sequence.hooks
Changes the order in which hooks are executed. Accepted values are: "stack", "list" and "parallel". Visit sequence.hooks for more information (default: "parallel")
sequence.setupFiles
- CLI:
--sequence.setupFiles <order> - Config: sequence.setupFiles
Changes the order in which setup files are executed. Accepted values are: "list" and "parallel". If set to "list", will run setup files in the order they are defined. If set to "parallel", will run setup files in parallel (default: "parallel")
inspect
- CLI:
--inspect [[host:]port] - Config: inspect
Enable Node.js inspector (default: 127.0.0.1:9229)
inspectBrk
- CLI:
--inspectBrk [[host:]port] - Config: inspectBrk
Enable Node.js inspector and break before the test starts
testTimeout
- CLI:
--testTimeout <timeout> - Config: testTimeout
Default timeout of a test in milliseconds (default: 5000)
hookTimeout
- CLI:
--hookTimeout <timeout> - Config: hookTimeout
Default hook timeout in milliseconds (default: 10000)
bail
- CLI:
--bail <number> - Config: bail
Stop test execution when given number of tests have failed (default: 0)
retry
- CLI:
--retry <times> - Config: retry
Retry the test specific number of times if it fails (default: 0)
diff
- CLI:
--diff <path> - Config: diff
Path to a diff config that will be used to generate diff interface
exclude
- CLI:
--exclude <glob> - Config: exclude
Additional file globs to be excluded from test
expandSnapshotDiff
- CLI:
--expandSnapshotDiff - Config: expandSnapshotDiff
Show full diff when snapshot fails
disableConsoleIntercept
- CLI:
--disableConsoleIntercept - Config: disableConsoleIntercept
Disable automatic interception of console logging (default: false)
typecheck.enabled
- CLI:
--typecheck.enabled - Config: typecheck.enabled
Enable typechecking alongside tests (default: false)
typecheck.only
- CLI:
--typecheck.only - Config: typecheck.only
Run only typecheck tests. This automatically enables typecheck (default: false)
typecheck.checker
- CLI:
--typecheck.checker <name> - Config: typecheck.checker
Specify the typechecker to use. Available values are: "tsc" and "vue-tsc" and a path to an executable (default: "tsc")
typecheck.allowJs
- CLI:
--typecheck.allowJs - Config: typecheck.allowJs
Allow JavaScript files to be typechecked. By default takes the value from tsconfig.json
typecheck.ignoreSourceErrors
- CLI:
--typecheck.ignoreSourceErrors - Config: typecheck.ignoreSourceErrors
Ignore type errors from source files
typecheck.tsconfig
- CLI:
--typecheck.tsconfig <path> - Config: typecheck.tsconfig
Path to a custom tsconfig file
project
- CLI:
--project <name> - Config: project
The name of the project to run if you are using Vitest workspace feature. This can be repeated for multiple projects: --project=1 --project=2. You can also filter projects using wildcards like --project=packages*
slowTestThreshold
- CLI:
--slowTestThreshold <threshold> - Config: slowTestThreshold
Threshold in milliseconds for a test to be considered slow (default: 300)
teardownTimeout
- CLI:
--teardownTimeout <timeout> - Config: teardownTimeout
Default timeout of a teardown function in milliseconds (default: 10000)
maxConcurrency
- CLI:
--maxConcurrency <number> - Config: maxConcurrency
Maximum number of concurrent tests in a suite (default: 5)
expect.requireAssertions
- CLI:
--expect.requireAssertions - Config: expect.requireAssertions
Require that all tests have at least one assertion
expect.poll.interval
- CLI:
--expect.poll.interval <interval> - Config: expect.poll.interval
Poll interval in milliseconds for expect.poll() assertions (default: 50)
expect.poll.timeout
- CLI:
--expect.poll.timeout <timeout> - Config: expect.poll.timeout
Poll timeout in milliseconds for expect.poll() assertions (default: 1000)
printConsoleTrace
- CLI:
--printConsoleTrace - Config: printConsoleTrace
Always print console stack traces
run
- CLI:
--run
Disable watch mode
color
- CLI:
--no-color
Removes colors from the console output
clearScreen
- CLI:
--clearScreen
Clear terminal screen when re-running tests during watch mode (default: true)
standalone
- CLI:
--standalone
Start Vitest without running tests. File filters will be ignored, tests will be running only on change (default: false)
changed
- Type:
boolean | string - Default: false
Run tests only against changed files. If no value is provided, it will run tests against uncommitted changes (including staged and unstaged).
To run tests against changes made in the last commit, you can use --changed HEAD~1. You can also pass commit hash (e.g. --changed 09a9920) or branch name (e.g. --changed origin/develop).
When used with code coverage the report will contain only the files that were related to the changes.
If paired with the forceRerunTriggers config option it will run the whole test suite if at least one of the files listed in the forceRerunTriggers list changes. By default, changes to the Vitest config file and package.json will always rerun the whole suite.
shard
- Type:
string - Default: disabled
Test suite shard to execute in a format of <index>/<count>, where
countis a positive integer, count of divided partsindexis a positive integer, index of divided part
This command will divide all tests into count equal parts, and will run only those that happen to be in an index part. For example, to split your tests suite into three parts, use this:
sh
vitest run --shard=1/3
vitest run --shard=2/3
vitest run --shard=3/3WARNING
You cannot use this option with --watch enabled (enabled in dev by default).
TIP
If --reporter=blob is used without an output file, the default path will include the current shard config to avoid collisions with other Vitest processes.
merge-reports
- Type:
boolean | string
Merges every blob report located in the specified folder (.vitest-reports by default). You can use any reporters with this command (except blob):
sh
vitest --merge-reports --reporter=junit