Vitest inherits Vite configuration options
Vitest uses Vite config and supports any configuration option from Vite, such as define for defining global variables or resolve.alias for defining aliases. These Vite options should be defined at the top level, not within the test property.
injectCjsGlobals purpose
The injectCjsGlobals option controls whether CommonJS module variables (module, exports, require, __filename, __dirname) are injected into every module processed by Vitest. When enabled (default), every file transformed by Vitest has access to these variables even if written using ESM syntax.
injectCjsGlobals config option type and default
The injectCjsGlobals configuration option has type boolean and a default value of true.
injectCjsGlobals CLI flags
The injectCjsGlobals option can be set via CLI using --no-inject-cjs-globals or --injectCjsGlobals=false.
injectCjsGlobals disabled behavior
When injectCjsGlobals is disabled, only modules detected as CommonJS receive the CommonJS variables. CommonJS modules always keep them because they are required to evaluate the module. Referencing CommonJS variables in an ES module throws a ReferenceError.
Module type detection algorithm
Vitest detects module type using three methods in order: (1) File extension - .cjs and .cts files are always CommonJS, .mjs and .mts files are always ES modules. (2) The type field in the nearest package.json - 'module' means ES module, 'commonjs' means CommonJS, lookup stops at the first package.json and never crosses node_modules boundary. (3) ESM syntax presence - if the file has no static import/export declarations and doesn't reference import.meta, it is treated as CommonJS. Dynamic imports are allowed in CommonJS, and type-only TypeScript imports are erased during transform, so they don't count as ESM syntax.
Syntax detection ignores Node.js flags
Vitest's syntax detection is always enabled and does not respect Node.js CLI flags that modify module type resolution, such as --no-experimental-detect-module, --input-type, or --experimental-default-type.
injectCjsGlobals example configuration
To disable injectCjsGlobals, use this configuration in vitest/config:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
injectCjsGlobals: false,
},
})
injectCjsGlobals doesn't affect externalized modules
The injectCjsGlobals option does not affect externalized modules which are always executed by the native runtime. Node.js provides CommonJS variables to externalized CommonJS modules on its own. Inlined CommonJS modules are not processed by Vite plugins even when injectCjsGlobals is enabled; require calls always leave the module runner.
isolate config option type and default
The isolate configuration option has type boolean with a default value of true.
isolate performance impact
Disabling the isolate option might improve performance if code doesn't rely on side effects, which is usually true for projects with node environment.
isolate purpose and behavior
The isolate option runs tests in an isolated environment. This option has no effect on vmThreads and vmForks pools.
isolate CLI flags
The isolate option can be controlled via CLI with flags --no-isolate and --isolate=false.
isolate per-project configuration
Isolation can be disabled for specific test files by using Vitest workspaces and disabling isolation per project.
logHeapUsage config option
The logHeapUsage configuration option is a boolean that controls whether heap usage is displayed after each test. It is useful for debugging memory leaks. The type is boolean, the default value is false, and it can be set via CLI using --logHeapUsage or --logHeapUsage=false.
maxConcurrency configuration option
maxConcurrency is a configuration option with type number and default value 5. It specifies the maximum number of tests and hooks that can run at the same time when using test.concurrent or describe.concurrent. The CLI accepts both --max-concurrency=10 and --maxConcurrency=10 formats.
maxConcurrency affects sequence.hooks execution
The hook execution order within a single group is controlled by sequence.hooks setting. When sequence.hooks is set to 'parallel', the execution is bounded by the same limit of maxConcurrency.
maxWorkers example with percentage
To configure maxWorkers with a percentage string in vitest.config.js:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
maxWorkers: '50%',
},
})
Or use the CLI: vitest --maxWorkers=50%
maxWorkers option type and default
The maxWorkers option has type number | string. The default value depends on the watch mode: if watch is disabled, it uses all available parallelism; if watch is enabled, it uses half of all available parallelism.
maxWorkers accepts number for worker count
The maxWorkers option accepts a number to spawn up to the specified number of workers.
maxWorkers uses os.availableParallelism
Vitest uses the Node.js os.availableParallelism() function to determine the maximum amount of parallelism available on the machine.
maxWorkers accepts percentage string for worker count
The maxWorkers option accepts a percentage string (e.g., '50%') which computes the worker count as the given percentage of the machine's available parallelism.
maxWorkers example with number
To configure maxWorkers with a number in vitest.config.js:
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
maxWorkers: 4,
},
})
Or use the CLI: vitest --maxWorkers=4
mockReset behavior with concurrent tests
When mockReset is enabled, it may cause problems with async concurrent tests. The completion of one test will clear the mock history and implementation for all mocks, including those currently being used by other tests in progress. This can lead to unexpected behavior in concurrent test scenarios.
mockReset example configuration
The following configuration enables mockReset: import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
mockReset: true,
},
})
mockReset type
The mockReset option accepts a boolean type.
mockReset default value
The mockReset option has a default value of false.
mockReset configuration option
The mockReset option is a boolean configuration parameter in Vitest test config. It determines whether Vitest automatically calls vi.resetAllMocks() before each test. When enabled, it clears mock history and resets each mock implementation. The default value is false.
mode config option
The mode option overrides Vite mode. It has type string, default value 'test', and can be set via CLI with --mode=staging.
name config object example
Example of setting name as an object with label and color:
```js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
name: {
label: 'unit',
color: 'blue',
},
},
})
```
name config option type
The name config option has type `string | { label: string; color?: LabelColor }`. It can be either a simple string or an object with a required label property and optional color property.
name config option purpose
The name option assigns a custom name to the test project or Vitest process. The name is visible in the CLI and UI, and available in the Node.js API via project.name.
name config color property
The color property in the name object can be one of: black, red, green, yellow, blue, magenta, cyan, or white. The displayed colors depend on the terminal's color scheme. In the UI, colors match their CSS equivalents.
name config string example
Example of setting name as a string:
```js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
name: 'unit',
},
})
```
name config multiple projects example
Example of using name to distinguish multiple projects:
```js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
projects: [
{
name: 'unit',
include: ['./test/*.unit.test.js'],
},
{
name: 'e2e',
include: ['./test/*.e2e.test.js'],
},
],
},
})
```
name config automatic assignment
Vitest automatically assigns a name when none is provided, using this resolution order: (1) If the project is specified by a config file or directory, Vitest uses the package.json's name field. (2) If there is no package.json, Vitest falls back to the project folder's basename. (3) If the project is defined inline in the projects array as an object, Vitest assigns a numeric name equal to that project's array index (0-based).
name config uniqueness constraint
Projects cannot have the same name. Vitest will throw an error during the config resolution if duplicate project names are detected.
name config browser instances example
Example of assigning names to different browser instances:
```js
import { defineConfig } from 'vitest/config'
import { playwright } from '@vitest/browser-playwright'
export default defineConfig({
test: {
browser: {
enabled: true,
provider: playwright(),
instances: [
{ browser: 'chromium', name: 'Chrome' },
{ browser: 'firefox', name: 'Firefox' },
],
},
},
})
```
name config browser instance inheritance
Browser instances inherit their parent project's name with the browser name appended in parentheses. For example, a project named 'browser' with a chromium instance will be shown as 'browser (chromium)'. If the parent project has no name, or instances are defined at the root level (not inside a named project), the instance name defaults to the browser value (e.g., 'chromium'). To override this behavior, set an explicit name on the instance.
onStackTrace option type and signature
The onStackTrace configuration option has type (error: Error, frame: ParsedStack) => boolean | void. It is a function that takes two arguments: an error object (which is a TestError) and a frame object (which is a ParsedStack), and returns either a boolean or void.
Error.stackTraceLimit consideration for stack trace size
The stack trace's total size is typically limited by V8's Error.stackTraceLimit number. Setting this to a high value in a test setup function can prevent stacks from being truncated.
onStackTrace example with ReferenceError and node_modules filtering
The following example shows how to use onStackTrace: for ReferenceError exceptions, return without filtering (show whole stack); for all other errors, return false when the frame file path includes 'node_modules' to filter them out:
```ts
import type { ParsedStack, TestError } from 'vitest'
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
onStackTrace(error: TestError, { file }: ParsedStack): boolean | void {
// If we've encountered a ReferenceError, show the whole stack.
if (error.name === 'ReferenceError') {
return
}
// Reject all frames from third party libraries.
if (file.includes('node_modules')) {
return false
}
},
},
})
```
onStackTrace use case for third-party filtering
onStackTrace can be useful for filtering out stack trace frames from third-party libraries to reduce noise in error reporting.
onStackTrace purpose and behavior
onStackTrace applies a filtering function to each frame of each stack trace when handling errors. It does not apply to stack traces printed by printConsoleTrace. Returning false from the function filters out a stack trace frame. Returning true or void includes the frame.
onUnhandledError callback configuration option
The onUnhandledError option accepts a function that filters unhandled errors. The callback receives an error parameter of type (TestError | Error) & { type: string }. The function should return a boolean or void. When the callback returns false or a falsy value, the error is filtered out and no longer affects the test run result. When no value is returned or true is returned, the error is reported normally. This callback is called on the main thread and does not have access to the test context.
dangerouslyIgnoreUnhandledErrors alternative option
For reporting unhandled errors without affecting the test outcome, use the dangerouslyIgnoreUnhandledErrors configuration option instead of onUnhandledError.
onUnhandledError example filtering specific error types
Example of using onUnhandledError to ignore specific error types:
```ts
import type { ParsedStack } from 'vitest'
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
onUnhandledError(error): boolean | void {
// Ignore all errors with the name "MySpecialError".
if (error.name === 'MySpecialError') {
return false
}
},
},
})
```
This example shows how to return false from the callback to filter out errors with a specific name, preventing them from affecting the test run result.
onUnhandledError available since Vitest 4.0.0
The onUnhandledError configuration option was introduced in Vitest version 4.0.0.
onUnhandledError type signature
The onUnhandledError option has type: function onUnhandledError(error: (TestError | Error) & { type: string }): boolean | void
onConsoleLog return value behavior
If onConsoleLog returns false, Vitest will not print the log to the console. Vitest ignores all other falsy values.
onConsoleLog example with third-party library filtering
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
onConsoleLog(log: string, type: 'stdout' | 'stderr'): boolean | void {
return !(log === 'message from third party library' && type === 'stdout')
},
},
})
This example filters out a specific message from a third-party library by returning false when the log matches 'message from third party library' and the type is 'stdout'.
onConsoleLog use case
onConsoleLog can be useful for filtering out logs from third-party libraries.
onConsoleLog config option signature
The onConsoleLog option is a function with signature: function onConsoleLog(log: string, type: 'stdout' | 'stderr', entity: TestModule | TestSuite | TestCase | undefined): boolean | void. It is a custom handler for console methods in tests.
open config option
The open configuration option has type boolean. Its default value is !process.env.CI, meaning it defaults to true unless running in a CI environment. It can be set via CLI with --open or --open=false flags. This option controls whether the Vitest UI automatically opens when it is enabled.
outputFile with multiple reporters
When using outputFile as an object (Record<string, string>) instead of a string, you can define individual outputs for each reporter when using multiple reporters.
outputFile config option type and CLI usage
The outputFile configuration option accepts type 'string | Record<string, string>'. The CLI accepts '--outputFile=<path>' or '--outputFile.json=./path'. This option writes test results to a file when '--reporter=json' or '--reporter=junit' option is also specified.
passWithNoTests behavior
When passWithNoTests is enabled, Vitest will not fail if no tests are found.
passWithNoTests option type and default
The passWithNoTests configuration option has type boolean with a default value of false.
passWithNoTests CLI flags
The passWithNoTests option can be set via CLI using the flags --passWithNoTests or --passWithNoTests=false.
printConsoleTrace option type and default
The printConsoleTrace configuration option has type boolean with a default value of false.