mirror of
https://github.com/vitest-dev/vitest.git
synced 2025-12-08 18:26:03 +00:00
docs: update structure (#8625)
This commit is contained in:
parent
da8b93aa53
commit
65292c3655
3
docs/.vitepress/components.d.ts
vendored
3
docs/.vitepress/components.d.ts
vendored
@ -12,11 +12,12 @@ declare module 'vue' {
|
|||||||
Box: typeof import('./components/Box.vue')['default']
|
Box: typeof import('./components/Box.vue')['default']
|
||||||
Contributors: typeof import('./components/Contributors.vue')['default']
|
Contributors: typeof import('./components/Contributors.vue')['default']
|
||||||
CourseLink: typeof import('./components/CourseLink.vue')['default']
|
CourseLink: typeof import('./components/CourseLink.vue')['default']
|
||||||
|
CRoot: typeof import('./components/CRoot.vue')['default']
|
||||||
Deprecated: typeof import('./components/Deprecated.vue')['default']
|
Deprecated: typeof import('./components/Deprecated.vue')['default']
|
||||||
|
Experimental: typeof import('./components/Experimental.vue')['default']
|
||||||
FeaturesList: typeof import('./components/FeaturesList.vue')['default']
|
FeaturesList: typeof import('./components/FeaturesList.vue')['default']
|
||||||
HomePage: typeof import('./components/HomePage.vue')['default']
|
HomePage: typeof import('./components/HomePage.vue')['default']
|
||||||
ListItem: typeof import('./components/ListItem.vue')['default']
|
ListItem: typeof import('./components/ListItem.vue')['default']
|
||||||
NonProjectOption: typeof import('./components/NonProjectOption.vue')['default']
|
|
||||||
Version: typeof import('./components/Version.vue')['default']
|
Version: typeof import('./components/Version.vue')['default']
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
5
docs/.vitepress/components/CRoot.vue
Normal file
5
docs/.vitepress/components/CRoot.vue
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<template>
|
||||||
|
<Badge type="warning" title="This options is only available in the top level config. You cannot specify it as an option of a test project." class="underline decoration-dotted cursor-help">
|
||||||
|
<div i-carbon:document-configuration class="my-1 -mx-1" />
|
||||||
|
</Badge>
|
||||||
|
</template>
|
||||||
@ -1,9 +1,5 @@
|
|||||||
<script setup lang="ts">
|
|
||||||
import { VPBadge } from 'vitepress/theme'
|
|
||||||
</script>
|
|
||||||
|
|
||||||
<template>
|
<template>
|
||||||
<VPBadge type="danger">
|
<Badge type="danger">
|
||||||
deprecated
|
deprecated
|
||||||
</VPBadge>
|
</Badge>
|
||||||
</template>
|
</template>
|
||||||
|
|||||||
5
docs/.vitepress/components/Experimental.vue
Normal file
5
docs/.vitepress/components/Experimental.vue
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
<template>
|
||||||
|
<Badge type="warning" title="This feature is experimental and does not follow SemVer." class="cursor-help">
|
||||||
|
experimental
|
||||||
|
</Badge>
|
||||||
|
</template>
|
||||||
@ -1,10 +0,0 @@
|
|||||||
<template>
|
|
||||||
<span
|
|
||||||
text-sm
|
|
||||||
text-orange
|
|
||||||
cursor-not-allowed
|
|
||||||
title="Not supported in workspace project config"
|
|
||||||
>
|
|
||||||
*
|
|
||||||
</span>
|
|
||||||
</template>
|
|
||||||
File diff suppressed because it is too large
Load Diff
@ -35,6 +35,12 @@ const skipConfig = new Set([
|
|||||||
'run',
|
'run',
|
||||||
'hideSkippedTests',
|
'hideSkippedTests',
|
||||||
'dom',
|
'dom',
|
||||||
|
'inspect',
|
||||||
|
'inspectBrk',
|
||||||
|
'project',
|
||||||
|
'ui',
|
||||||
|
'browser.name',
|
||||||
|
'browser.fileParallelism',
|
||||||
])
|
])
|
||||||
|
|
||||||
function resolveOptions(options: CLIOptions<any>, parentName?: string) {
|
function resolveOptions(options: CLIOptions<any>, parentName?: string) {
|
||||||
@ -76,8 +82,9 @@ const options = resolveOptions(cliOptionsConfig)
|
|||||||
const template = options.map((option) => {
|
const template = options.map((option) => {
|
||||||
const title = option.title
|
const title = option.title
|
||||||
const cli = option.cli
|
const cli = option.cli
|
||||||
const config = skipConfig.has(title) ? '' : `[${title}](${title.includes('browser.') ? '/guide/browser/config' : '/config/'}#${title.toLowerCase().replace(/\./g, '-')})`
|
const [page, ...hash] = (title.startsWith('browser.') ? title.slice(8) : title).toLowerCase().split('.')
|
||||||
return `### ${title}\n\n- **CLI:** ${cli}\n${config ? `- **Config:** ${config}\n` : ''}\n${option.description}\n`
|
const config = skipConfig.has(title) ? '' : `[${title}](${title.includes('browser.') ? '/config/browser/' : '/config/'}${page}${hash.length ? `#${[page, ...hash].join('-')}` : ''})`
|
||||||
|
return `### ${title}\n\n- **CLI:** ${cli}\n${config ? `- **Config:** ${config}\n` : ''}\n${option.description.replace(/https:\/\/vitest\.dev\//g, '/')}\n`
|
||||||
}).join('\n')
|
}).join('\n')
|
||||||
|
|
||||||
writeFileSync(cliTablePath, template, 'utf-8')
|
writeFileSync(cliTablePath, template, 'utf-8')
|
||||||
|
|||||||
@ -6,7 +6,9 @@ import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client'
|
|||||||
import { h } from 'vue'
|
import { h } from 'vue'
|
||||||
import HomePage from '../components/HomePage.vue'
|
import HomePage from '../components/HomePage.vue'
|
||||||
import Version from '../components/Version.vue'
|
import Version from '../components/Version.vue'
|
||||||
|
import CRoot from '../components/CRoot.vue'
|
||||||
import Deprecated from '../components/Deprecated.vue'
|
import Deprecated from '../components/Deprecated.vue'
|
||||||
|
import Experimental from '../components/Experimental.vue'
|
||||||
import '../style/main.css'
|
import '../style/main.css'
|
||||||
import '../style/vars.css'
|
import '../style/vars.css'
|
||||||
import 'uno.css'
|
import 'uno.css'
|
||||||
@ -24,8 +26,29 @@ export default {
|
|||||||
'home-features-after': () => h(HomePage),
|
'home-features-after': () => h(HomePage),
|
||||||
})
|
})
|
||||||
},
|
},
|
||||||
enhanceApp({ app }) {
|
enhanceApp({ app, router }) {
|
||||||
|
router.onBeforeRouteChange = (to) => {
|
||||||
|
if (typeof location === 'undefined') {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
const url = new URL(to, location.href)
|
||||||
|
if (!url.hash) {
|
||||||
|
return true
|
||||||
|
}
|
||||||
|
if (url.pathname === '/config' || url.pathname === '/config/' || url.pathname === '/config.html') {
|
||||||
|
const [page, ...hash] = (url.hash.startsWith('#browser.') ? url.hash.slice(9) : url.hash.slice(1)).toLowerCase().split('-')
|
||||||
|
setTimeout(() => { router.go(`/config/${page}${hash.length ? `#${[page, ...hash].join('-')}` : ''}`) })
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (url.pathname === '/guide/browser/config' || url.pathname === '/guide/browser/config/' || url.pathname === '/guide/browser/config.html') {
|
||||||
|
const [page, ...hash] = url.hash.slice('#browser.'.length).toLowerCase().split('-')
|
||||||
|
setTimeout(() => { router.go(`/config/browser/${page}${hash.length ? `#${[page, ...hash].join('-')}` : ''}`) })
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
}
|
||||||
app.component('Version', Version)
|
app.component('Version', Version)
|
||||||
|
app.component('CRoot', CRoot)
|
||||||
|
app.component('Experimental', Experimental)
|
||||||
app.component('Deprecated', Deprecated)
|
app.component('Deprecated', Deprecated)
|
||||||
app.use(TwoslashFloatingVue)
|
app.use(TwoslashFloatingVue)
|
||||||
enhanceAppWithTabs(app)
|
enhanceAppWithTabs(app)
|
||||||
|
|||||||
@ -1,4 +1,4 @@
|
|||||||
# Task Metadata
|
# Task Metadata <Badge type="danger">advanced</Badge>
|
||||||
|
|
||||||
If you are developing a custom reporter or using Vitest Node.js API, you might find it useful to pass data from tests that are being executed in various contexts to your reporter or custom Vitest handler.
|
If you are developing a custom reporter or using Vitest Node.js API, you might find it useful to pass data from tests that are being executed in various contexts to your reporter or custom Vitest handler.
|
||||||
|
|
||||||
@ -53,7 +53,7 @@ Vitest re-exports all Vite type-only imports via a `Vite` namespace, which you c
|
|||||||
```
|
```
|
||||||
:::
|
:::
|
||||||
|
|
||||||
Unlike [`reporter.onInit`](/advanced/api/reporters#oninit), this hooks runs early in Vitest lifecycle allowing you to make changes to configuration like `coverage` and `reporters`. A more notable change is that you can manipulate the global config from a [test project](/guide/projects) if your plugin is defined in the project and not in the global config.
|
Unlike [`reporter.onInit`](/api/advanced/reporters#oninit), this hooks runs early in Vitest lifecycle allowing you to make changes to configuration like `coverage` and `reporters`. A more notable change is that you can manipulate the global config from a [test project](/guide/projects) if your plugin is defined in the project and not in the global config.
|
||||||
|
|
||||||
## Context
|
## Context
|
||||||
|
|
||||||
@ -32,7 +32,7 @@ Tests and suites within a single module will be reported in order unless they we
|
|||||||
|
|
||||||
Note that since test modules can run in parallel, Vitest will report them in parallel.
|
Note that since test modules can run in parallel, Vitest will report them in parallel.
|
||||||
|
|
||||||
This guide lists all supported reporter methods. However, don't forget that instead of creating your own reporter, you can [extend existing one](/advanced/reporters) instead:
|
This guide lists all supported reporter methods. However, don't forget that instead of creating your own reporter, you can [extend existing one](/guide/advanced/reporters) instead:
|
||||||
|
|
||||||
```ts [custom-reporter.js]
|
```ts [custom-reporter.js]
|
||||||
import { BaseReporter } from 'vitest/reporters'
|
import { BaseReporter } from 'vitest/reporters'
|
||||||
@ -51,13 +51,13 @@ export default class CustomReporter extends BaseReporter {
|
|||||||
function onInit(vitest: Vitest): Awaitable<void>
|
function onInit(vitest: Vitest): Awaitable<void>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method is called when [Vitest](/advanced/api/vitest) was initiated or started, but before the tests were filtered.
|
This method is called when [Vitest](/api/advanced/vitest) was initiated or started, but before the tests were filtered.
|
||||||
|
|
||||||
::: info
|
::: info
|
||||||
Internally this method is called inside [`vitest.start`](/advanced/api/vitest#start), [`vitest.init`](/advanced/api/vitest#init) or [`vitest.mergeReports`](/advanced/api/vitest#mergereports). If you are using programmatic API, make sure to call either one depending on your needs before calling [`vitest.runTestSpecifications`](/advanced/api/vitest#runtestspecifications), for example. Built-in CLI will always run methods in correct order.
|
Internally this method is called inside [`vitest.start`](/api/advanced/vitest#start), [`vitest.init`](/api/advanced/vitest#init) or [`vitest.mergeReports`](/api/advanced/vitest#mergereports). If you are using programmatic API, make sure to call either one depending on your needs before calling [`vitest.runTestSpecifications`](/api/advanced/vitest#runtestspecifications), for example. Built-in CLI will always run methods in correct order.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
Note that you can also get access to `vitest` instance from test cases, suites and test modules via a [`project`](/advanced/api/test-project) property, but it might also be useful to store a reference to `vitest` in this method.
|
Note that you can also get access to `vitest` instance from test cases, suites and test modules via a [`project`](/api/advanced/test-project) property, but it might also be useful to store a reference to `vitest` in this method.
|
||||||
|
|
||||||
::: details Example
|
::: details Example
|
||||||
```ts
|
```ts
|
||||||
@ -99,7 +99,7 @@ function onTestRunStart(
|
|||||||
): Awaitable<void>
|
): Awaitable<void>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method is called when a new test run has started. It receives an array of [test specifications](/advanced/api/test-specification) scheduled to run. This array is readonly and available only for information purposes.
|
This method is called when a new test run has started. It receives an array of [test specifications](/api/advanced/test-specification) scheduled to run. This array is readonly and available only for information purposes.
|
||||||
|
|
||||||
If Vitest didn't find any test files to run, this event will be invoked with an empty array, and then [`onTestRunEnd`](#ontestrunend) will be called immediately after.
|
If Vitest didn't find any test files to run, this event will be invoked with an empty array, and then [`onTestRunEnd`](#ontestrunend) will be called immediately after.
|
||||||
|
|
||||||
@ -133,7 +133,7 @@ function onTestRunEnd(
|
|||||||
|
|
||||||
This method is called after all tests have finished running and the coverage merged all reports, if it's enabled. Note that you can get the coverage information in [`onCoverage`](#oncoverage) hook.
|
This method is called after all tests have finished running and the coverage merged all reports, if it's enabled. Note that you can get the coverage information in [`onCoverage`](#oncoverage) hook.
|
||||||
|
|
||||||
It receives a readonly list of test modules. You can iterate over it via a [`testModule.children`](/advanced/api/test-collection) property to report the state and errors, if any.
|
It receives a readonly list of test modules. You can iterate over it via a [`testModule.children`](/api/advanced/test-collection) property to report the state and errors, if any.
|
||||||
|
|
||||||
The second argument is a readonly list of unhandled errors that Vitest wasn't able to attribute to any test. These can happen outside of the test run because of an error in a plugin, or inside the test run as a side-effect of a non-awaited function (for example, a timeout that threw an error after the test has finished running).
|
The second argument is a readonly list of unhandled errors that Vitest wasn't able to attribute to any test. These can happen outside of the test run because of an error in a plugin, or inside the test run as a side-effect of a non-awaited function (for example, a timeout that threw an error after the test has finished running).
|
||||||
|
|
||||||
@ -141,7 +141,7 @@ The third argument indicated why the test run was finished:
|
|||||||
|
|
||||||
- `passed`: test run was finished normally and there are no errors
|
- `passed`: test run was finished normally and there are no errors
|
||||||
- `failed`: test run has at least one error (due to a syntax error during collection or an actual error during test execution)
|
- `failed`: test run has at least one error (due to a syntax error during collection or an actual error during test execution)
|
||||||
- `interrupted`: test was interrupted by [`vitest.cancelCurrentRun`](/advanced/api/vitest#cancelcurrentrun) call or `Ctrl+C` was pressed in the terminal (note that it's still possible to have failed tests in this case)
|
- `interrupted`: test was interrupted by [`vitest.cancelCurrentRun`](/api/advanced/vitest#cancelcurrentrun) call or `Ctrl+C` was pressed in the terminal (note that it's still possible to have failed tests in this case)
|
||||||
|
|
||||||
If Vitest didn't find any test files to run, this event will be invoked with empty arrays of modules and errors, and the state will depend on the value of [`config.passWithNoTests`](/config/#passwithnotests).
|
If Vitest didn't find any test files to run, this event will be invoked with empty arrays of modules and errors, and the state will depend on the value of [`config.passWithNoTests`](/config/#passwithnotests).
|
||||||
|
|
||||||
@ -210,7 +210,7 @@ If Vitest didn't perform any coverage, this hook is not called.
|
|||||||
function onTestModuleQueued(testModule: TestModule): Awaitable<void>
|
function onTestModuleQueued(testModule: TestModule): Awaitable<void>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method is called right before Vitest imports the setup file and the test module itself. This means that `testModule` will have no [`children`](/advanced/api/test-suite#children) yet, but you can start reporting it as the next test to run.
|
This method is called right before Vitest imports the setup file and the test module itself. This means that `testModule` will have no [`children`](/api/advanced/test-suite#children) yet, but you can start reporting it as the next test to run.
|
||||||
|
|
||||||
## onTestModuleCollected
|
## onTestModuleCollected
|
||||||
|
|
||||||
@ -218,7 +218,7 @@ This method is called right before Vitest imports the setup file and the test mo
|
|||||||
function onTestModuleCollected(testModule: TestModule): Awaitable<void>
|
function onTestModuleCollected(testModule: TestModule): Awaitable<void>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method is called when all tests inside the file were collected, meaning [`testModule.children`](/advanced/api/test-suite#children) collection is populated, but tests don't have any results yet.
|
This method is called when all tests inside the file were collected, meaning [`testModule.children`](/api/advanced/test-suite#children) collection is populated, but tests don't have any results yet.
|
||||||
|
|
||||||
## onTestModuleStart
|
## onTestModuleStart
|
||||||
|
|
||||||
@ -226,7 +226,7 @@ This method is called when all tests inside the file were collected, meaning [`t
|
|||||||
function onTestModuleStart(testModule: TestModule): Awaitable<void>
|
function onTestModuleStart(testModule: TestModule): Awaitable<void>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method is called right after [`onTestModuleCollected`](#ontestmodulecollected) unless Vitest runs in collection mode ([`vitest.collect()`](/advanced/api/vitest#collect) or `vitest collect` in the CLI), in this case it will not be called at all because there are no tests to run.
|
This method is called right after [`onTestModuleCollected`](#ontestmodulecollected) unless Vitest runs in collection mode ([`vitest.collect()`](/api/advanced/vitest#collect) or `vitest collect` in the CLI), in this case it will not be called at all because there are no tests to run.
|
||||||
|
|
||||||
## onTestModuleEnd
|
## onTestModuleEnd
|
||||||
|
|
||||||
@ -234,7 +234,7 @@ This method is called right after [`onTestModuleCollected`](#ontestmodulecollect
|
|||||||
function onTestModuleEnd(testModule: TestModule): Awaitable<void>
|
function onTestModuleEnd(testModule: TestModule): Awaitable<void>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method is called when every test in the module finished running. This means, every test inside [`testModule.children`](/advanced/api/test-suite#children) will have a `test.result()` that is not equal to `pending`.
|
This method is called when every test in the module finished running. This means, every test inside [`testModule.children`](/api/advanced/test-suite#children) will have a `test.result()` that is not equal to `pending`.
|
||||||
|
|
||||||
## onHookStart
|
## onHookStart
|
||||||
|
|
||||||
@ -249,9 +249,9 @@ This method is called when any of these hooks have started running:
|
|||||||
- `beforeEach`
|
- `beforeEach`
|
||||||
- `afterEach`
|
- `afterEach`
|
||||||
|
|
||||||
If `beforeAll` or `afterAll` are started, the `entity` will be either [`TestSuite`](/advanced/api/test-suite) or [`TestModule`](/advanced/api/test-module).
|
If `beforeAll` or `afterAll` are started, the `entity` will be either [`TestSuite`](/api/advanced/test-suite) or [`TestModule`](/api/advanced/test-module).
|
||||||
|
|
||||||
If `beforeEach` or `afterEach` are started, the `entity` will always be [`TestCase`](/advanced/api/test-case).
|
If `beforeEach` or `afterEach` are started, the `entity` will always be [`TestCase`](/api/advanced/test-case).
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
`onHookStart` method will not be called if the hook did not run during the test run.
|
`onHookStart` method will not be called if the hook did not run during the test run.
|
||||||
@ -270,9 +270,9 @@ This method is called when any of these hooks have finished running:
|
|||||||
- `beforeEach`
|
- `beforeEach`
|
||||||
- `afterEach`
|
- `afterEach`
|
||||||
|
|
||||||
If `beforeAll` or `afterAll` have finished, the `entity` will be either [`TestSuite`](/advanced/api/test-suite) or [`TestModule`](/advanced/api/test-module).
|
If `beforeAll` or `afterAll` have finished, the `entity` will be either [`TestSuite`](/api/advanced/test-suite) or [`TestModule`](/api/advanced/test-module).
|
||||||
|
|
||||||
If `beforeEach` or `afterEach` have finished, the `entity` will always be [`TestCase`](/advanced/api/test-case).
|
If `beforeEach` or `afterEach` have finished, the `entity` will always be [`TestCase`](/api/advanced/test-case).
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
`onHookEnd` method will not be called if the hook did not run during the test run.
|
`onHookEnd` method will not be called if the hook did not run during the test run.
|
||||||
@ -307,7 +307,7 @@ function onTestCaseReady(testCase: TestCase): Awaitable<void>
|
|||||||
This method is called before the test starts to run or it was skipped. Note that `beforeEach` and `afterEach` hooks are considered part of the test because they can influence the result.
|
This method is called before the test starts to run or it was skipped. Note that `beforeEach` and `afterEach` hooks are considered part of the test because they can influence the result.
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
Notice that it's possible to have [`testCase.result()`](/advanced/api/test-case#result) with `passed` or `failed` state already when `onTestCaseReady` is called. This can happen if test was running too fast and both `onTestCaseReady` and `onTestCaseResult` were scheduled to run in the same microtask.
|
Notice that it's possible to have [`testCase.result()`](/api/advanced/test-case#result) with `passed` or `failed` state already when `onTestCaseReady` is called. This can happen if test was running too fast and both `onTestCaseReady` and `onTestCaseResult` were scheduled to run in the same microtask.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## onTestCaseResult
|
## onTestCaseResult
|
||||||
@ -318,7 +318,7 @@ function onTestCaseResult(testCase: TestCase): Awaitable<void>
|
|||||||
|
|
||||||
This method is called when the test has finished running or was just skipped. Note that this will be called after the `afterEach` hook is finished, if there are any.
|
This method is called when the test has finished running or was just skipped. Note that this will be called after the `afterEach` hook is finished, if there are any.
|
||||||
|
|
||||||
At this point, [`testCase.result()`](/advanced/api/test-case#result) will have non-pending state.
|
At this point, [`testCase.result()`](/api/advanced/test-case#result) will have non-pending state.
|
||||||
|
|
||||||
## onTestAnnotate <Version>3.2.0</Version> {#ontestannotate}
|
## onTestAnnotate <Version>3.2.0</Version> {#ontestannotate}
|
||||||
|
|
||||||
@ -1,4 +1,4 @@
|
|||||||
# Runner API
|
# Runner API <Badge type="danger">advanced</Badge>
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
This is advanced API. If you just want to [run tests](/guide/), you probably don't need this. It is primarily used by library authors.
|
This is advanced API. If you just want to [run tests](/guide/), you probably don't need this. It is primarily used by library authors.
|
||||||
@ -150,7 +150,7 @@ Snapshot support and some other features depend on the runner. If you don't want
|
|||||||
## Tasks
|
## Tasks
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
The "Runner Tasks API" is experimental and should primarily be used only in the test runtime. Vitest also exposes the ["Reported Tasks API"](/advanced/api/test-module), which should be preferred when working in the main thread (inside the reporter, for example).
|
The "Runner Tasks API" is experimental and should primarily be used only in the test runtime. Vitest also exposes the ["Reported Tasks API"](/api/advanced/test-module), which should be preferred when working in the main thread (inside the reporter, for example).
|
||||||
|
|
||||||
The team is currently discussing if "Runner Tasks" should be replaced by "Reported Tasks" in the future.
|
The team is currently discussing if "Runner Tasks" should be replaced by "Reported Tasks" in the future.
|
||||||
:::
|
:::
|
||||||
@ -1,6 +1,6 @@
|
|||||||
# TestCase
|
# TestCase
|
||||||
|
|
||||||
The `TestCase` class represents a single test. This class is only available in the main thread. Refer to the ["Runner API"](/advanced/runner#tasks) if you are working with runtime tasks.
|
The `TestCase` class represents a single test. This class is only available in the main thread. Refer to the ["Runner API"](/api/advanced/runner#tasks) if you are working with runtime tasks.
|
||||||
|
|
||||||
The `TestCase` instance always has a `type` property with the value of `test`. You can use it to distinguish between different task types:
|
The `TestCase` instance always has a `type` property with the value of `test`. You can use it to distinguish between different task types:
|
||||||
|
|
||||||
@ -12,11 +12,11 @@ if (task.type === 'test') {
|
|||||||
|
|
||||||
## project
|
## project
|
||||||
|
|
||||||
This references the [`TestProject`](/advanced/api/test-project) that the test belongs to.
|
This references the [`TestProject`](/api/advanced/test-project) that the test belongs to.
|
||||||
|
|
||||||
## module
|
## module
|
||||||
|
|
||||||
This is a direct reference to the [`TestModule`](/advanced/api/test-module) where the test is defined.
|
This is a direct reference to the [`TestModule`](/api/advanced/test-module) where the test is defined.
|
||||||
|
|
||||||
## name
|
## name
|
||||||
|
|
||||||
@ -49,7 +49,7 @@ describe('the validation logic', () => {
|
|||||||
|
|
||||||
## id
|
## id
|
||||||
|
|
||||||
This is test's unique identifier. This ID is deterministic and will be the same for the same test across multiple runs. The ID is based on the [project](/advanced/api/test-project) name, module ID and test order.
|
This is test's unique identifier. This ID is deterministic and will be the same for the same test across multiple runs. The ID is based on the [project](/api/advanced/test-project) name, module ID and test order.
|
||||||
|
|
||||||
The ID looks like this:
|
The ID looks like this:
|
||||||
|
|
||||||
@ -93,7 +93,7 @@ test('the validation works correctly', () => {
|
|||||||
|
|
||||||
## parent
|
## parent
|
||||||
|
|
||||||
Parent [suite](/advanced/api/test-suite). If the test was called directly inside the [module](/advanced/api/test-module), the parent will be the module itself.
|
Parent [suite](/api/advanced/test-suite). If the test was called directly inside the [module](/api/advanced/test-module), the parent will be the module itself.
|
||||||
|
|
||||||
## options
|
## options
|
||||||
|
|
||||||
@ -125,7 +125,7 @@ Checks if the test did not fail the suite. If the test is not finished yet or wa
|
|||||||
function meta(): TaskMeta
|
function meta(): TaskMeta
|
||||||
```
|
```
|
||||||
|
|
||||||
Custom [metadata](/advanced/metadata) that was attached to the test during its execution. The meta can be attached by assigning a property to the `ctx.task.meta` object during a test run:
|
Custom [metadata](/api/advanced/metadata) that was attached to the test during its execution. The meta can be attached by assigning a property to the `ctx.task.meta` object during a test run:
|
||||||
|
|
||||||
```ts {3,6}
|
```ts {3,6}
|
||||||
import { test } from 'vitest'
|
import { test } from 'vitest'
|
||||||
@ -1,6 +1,6 @@
|
|||||||
# TestCollection
|
# TestCollection
|
||||||
|
|
||||||
`TestCollection` represents a collection of top-level [suites](/advanced/api/test-suite) and [tests](/advanced/api/test-case) in a suite or a module. It also provides useful methods to iterate over itself.
|
`TestCollection` represents a collection of top-level [suites](/api/advanced/test-suite) and [tests](/api/advanced/test-case) in a suite or a module. It also provides useful methods to iterate over itself.
|
||||||
|
|
||||||
::: info
|
::: info
|
||||||
Most methods return an iterator instead of an array for better performance in case you don't need every item in the collection. If you prefer working with array, you can spread the iterator: `[...children.allSuites()]`.
|
Most methods return an iterator instead of an array for better performance in case you don't need every item in the collection. If you prefer working with array, you can spread the iterator: `[...children.allSuites()]`.
|
||||||
@ -1,6 +1,6 @@
|
|||||||
# TestModule
|
# TestModule
|
||||||
|
|
||||||
The `TestModule` class represents a single module in a single project. This class is only available in the main thread. Refer to the ["Runner API"](/advanced/runner#tasks) if you are working with runtime tasks.
|
The `TestModule` class represents a single module in a single project. This class is only available in the main thread. Refer to the ["Runner API"](/api/advanced/runner#tasks) if you are working with runtime tasks.
|
||||||
|
|
||||||
The `TestModule` instance always has a `type` property with the value of `module`. You can use it to distinguish between different task types:
|
The `TestModule` instance always has a `type` property with the value of `module`. You can use it to distinguish between different task types:
|
||||||
|
|
||||||
@ -11,7 +11,7 @@ if (task.type === 'module') {
|
|||||||
```
|
```
|
||||||
|
|
||||||
::: warning Extending Suite Methods
|
::: warning Extending Suite Methods
|
||||||
The `TestModule` class inherits all methods and properties from the [`TestSuite`](/advanced/api/test-suite). This guide will only list methods and properties unique to the `TestModule`.
|
The `TestModule` class inherits all methods and properties from the [`TestSuite`](/api/advanced/test-suite). This guide will only list methods and properties unique to the `TestModule`.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## moduleId
|
## moduleId
|
||||||
@ -40,7 +40,7 @@ Module id relative to the project. This is the same as `task.name` in the deprec
|
|||||||
function state(): TestModuleState
|
function state(): TestModuleState
|
||||||
```
|
```
|
||||||
|
|
||||||
Works the same way as [`testSuite.state()`](/advanced/api/test-suite#state), but can also return `queued` if module wasn't executed yet.
|
Works the same way as [`testSuite.state()`](/api/advanced/test-suite#state), but can also return `queued` if module wasn't executed yet.
|
||||||
|
|
||||||
## meta <Version>3.1.0</Version> {#meta}
|
## meta <Version>3.1.0</Version> {#meta}
|
||||||
|
|
||||||
@ -48,7 +48,7 @@ Works the same way as [`testSuite.state()`](/advanced/api/test-suite#state), but
|
|||||||
function meta(): TaskMeta
|
function meta(): TaskMeta
|
||||||
```
|
```
|
||||||
|
|
||||||
Custom [metadata](/advanced/metadata) that was attached to the module during its execution or collection. The meta can be attached by assigning a property to the `task.meta` object during a test run:
|
Custom [metadata](/api/advanced/metadata) that was attached to the module during its execution or collection. The meta can be attached by assigning a property to the `task.meta` object during a test run:
|
||||||
|
|
||||||
```ts {5,10}
|
```ts {5,10}
|
||||||
import { test } from 'vitest'
|
import { test } from 'vitest'
|
||||||
@ -51,12 +51,12 @@ export default defineConfig({
|
|||||||
:::
|
:::
|
||||||
|
|
||||||
::: info
|
::: info
|
||||||
If the [root project](/advanced/api/vitest#getroottestproject) is not part of user projects, its `name` will not be resolved.
|
If the [root project](/api/advanced/vitest#getroottestproject) is not part of user projects, its `name` will not be resolved.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## vitest
|
## vitest
|
||||||
|
|
||||||
`vitest` references the global [`Vitest`](/advanced/api/vitest) process.
|
`vitest` references the global [`Vitest`](/api/advanced/vitest) process.
|
||||||
|
|
||||||
## serializedConfig
|
## serializedConfig
|
||||||
|
|
||||||
@ -78,7 +78,7 @@ project.serializedConfig === project.serializedConfig // ❌
|
|||||||
|
|
||||||
## globalConfig
|
## globalConfig
|
||||||
|
|
||||||
The test config that [`Vitest`](/advanced/api/vitest) was initialized with. If this is the [root project](/advanced/api/vitest#getroottestproject), `globalConfig` and `config` will reference the same object. This config is useful for values that cannot be set on the project level, like `coverage` or `reporters`.
|
The test config that [`Vitest`](/api/advanced/vitest) was initialized with. If this is the [root project](/api/advanced/vitest#getroottestproject), `globalConfig` and `config` will reference the same object. This config is useful for values that cannot be set on the project level, like `coverage` or `reporters`.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import type { ResolvedConfig } from 'vitest/node'
|
import type { ResolvedConfig } from 'vitest/node'
|
||||||
@ -179,7 +179,7 @@ function createSpecification(
|
|||||||
): TestSpecification
|
): TestSpecification
|
||||||
```
|
```
|
||||||
|
|
||||||
Create a [test specification](/advanced/api/test-specification) that can be used in [`vitest.runTestSpecifications`](/advanced/api/vitest#runtestspecifications). Specification scopes the test file to a specific `project` and test `locations` (optional). Test [locations](/advanced/api/test-case#location) are code lines where the test is defined in the source code. If locations are provided, Vitest will only run tests defined on those lines. Note that if [`testNamePattern`](/config/#testnamepattern) is defined, then it will also be applied.
|
Create a [test specification](/api/advanced/test-specification) that can be used in [`vitest.runTestSpecifications`](/api/advanced/vitest#runtestspecifications). Specification scopes the test file to a specific `project` and test `locations` (optional). Test [locations](/api/advanced/test-case#location) are code lines where the test is defined in the source code. If locations are provided, Vitest will only run tests defined on those lines. Note that if [`testNamePattern`](/config/#testnamepattern) is defined, then it will also be applied.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { createVitest } from 'vitest/node'
|
import { createVitest } from 'vitest/node'
|
||||||
@ -195,7 +195,7 @@ await vitest.runTestSpecifications([specification])
|
|||||||
```
|
```
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
`createSpecification` expects resolved [module ID](/advanced/api/test-specification#moduleid). It doesn't auto-resolve the file or check that it exists on the file system.
|
`createSpecification` expects resolved [module ID](/api/advanced/test-specification#moduleid). It doesn't auto-resolve the file or check that it exists on the file system.
|
||||||
|
|
||||||
Also note that `project.createSpecification` always returns a new instance.
|
Also note that `project.createSpecification` always returns a new instance.
|
||||||
:::
|
:::
|
||||||
@ -225,7 +225,7 @@ function globTestFiles(filters?: string[]): {
|
|||||||
|
|
||||||
Globs all test files. This function returns an object with regular tests and typecheck tests.
|
Globs all test files. This function returns an object with regular tests and typecheck tests.
|
||||||
|
|
||||||
This method accepts `filters`. Filters can only a part of the file path, unlike in other methods on the [`Vitest`](/advanced/api/vitest) instance:
|
This method accepts `filters`. Filters can only a part of the file path, unlike in other methods on the [`Vitest`](/api/advanced/vitest) instance:
|
||||||
|
|
||||||
```js
|
```js
|
||||||
project.globTestFiles(['foo']) // ✅
|
project.globTestFiles(['foo']) // ✅
|
||||||
@ -298,7 +298,7 @@ Internally, Vitest uses this method to import global setups, custom coverage pro
|
|||||||
function onTestsRerun(cb: OnTestsRerunHandler): void
|
function onTestsRerun(cb: OnTestsRerunHandler): void
|
||||||
```
|
```
|
||||||
|
|
||||||
This is a shorthand for [`project.vitest.onTestsRerun`](/advanced/api/vitest#ontestsrerun). It accepts a callback that will be awaited when the tests have been scheduled to rerun (usually, due to a file change).
|
This is a shorthand for [`project.vitest.onTestsRerun`](/api/advanced/vitest#ontestsrerun). It accepts a callback that will be awaited when the tests have been scheduled to rerun (usually, due to a file change).
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
project.onTestsRerun((specs) => {
|
project.onTestsRerun((specs) => {
|
||||||
@ -2,7 +2,7 @@
|
|||||||
|
|
||||||
The `TestSpecification` class describes what module to run as a test and its parameters.
|
The `TestSpecification` class describes what module to run as a test and its parameters.
|
||||||
|
|
||||||
You can only create a specification by calling [`createSpecification`](/advanced/api/test-project#createspecification) method on a test project:
|
You can only create a specification by calling [`createSpecification`](/api/advanced/test-project#createspecification) method on a test project:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const specification = project.createSpecification(
|
const specification = project.createSpecification(
|
||||||
@ -15,11 +15,11 @@ const specification = project.createSpecification(
|
|||||||
|
|
||||||
## taskId
|
## taskId
|
||||||
|
|
||||||
[Test module's](/advanced/api/test-suite#id) identifier.
|
[Test module's](/api/advanced/test-suite#id) identifier.
|
||||||
|
|
||||||
## project
|
## project
|
||||||
|
|
||||||
This references the [`TestProject`](/advanced/api/test-project) that the test module belongs to.
|
This references the [`TestProject`](/api/advanced/test-project) that the test module belongs to.
|
||||||
|
|
||||||
## moduleId
|
## moduleId
|
||||||
|
|
||||||
@ -33,7 +33,7 @@ The ID of the module in Vite's module graph. Usually, it's an absolute file path
|
|||||||
|
|
||||||
## testModule
|
## testModule
|
||||||
|
|
||||||
Instance of [`TestModule`](/advanced/api/test-module) associated with the specification. If test wasn't queued yet, this will be `undefined`.
|
Instance of [`TestModule`](/api/advanced/test-module) associated with the specification. If test wasn't queued yet, this will be `undefined`.
|
||||||
|
|
||||||
## pool <Badge type="warning">experimental</Badge> {#pool}
|
## pool <Badge type="warning">experimental</Badge> {#pool}
|
||||||
|
|
||||||
@ -1,6 +1,6 @@
|
|||||||
# TestSuite
|
# TestSuite
|
||||||
|
|
||||||
The `TestSuite` class represents a single suite. This class is only available in the main thread. Refer to the ["Runner API"](/advanced/runner#tasks) if you are working with runtime tasks.
|
The `TestSuite` class represents a single suite. This class is only available in the main thread. Refer to the ["Runner API"](/api/advanced/runner#tasks) if you are working with runtime tasks.
|
||||||
|
|
||||||
The `TestSuite` instance always has a `type` property with the value of `suite`. You can use it to distinguish between different task types:
|
The `TestSuite` instance always has a `type` property with the value of `suite`. You can use it to distinguish between different task types:
|
||||||
|
|
||||||
@ -12,11 +12,11 @@ if (task.type === 'suite') {
|
|||||||
|
|
||||||
## project
|
## project
|
||||||
|
|
||||||
This references the [`TestProject`](/advanced/api/test-project) that the test belongs to.
|
This references the [`TestProject`](/api/advanced/test-project) that the test belongs to.
|
||||||
|
|
||||||
## module
|
## module
|
||||||
|
|
||||||
This is a direct reference to the [`TestModule`](/advanced/api/test-module) where the test is defined.
|
This is a direct reference to the [`TestModule`](/api/advanced/test-module) where the test is defined.
|
||||||
|
|
||||||
## name
|
## name
|
||||||
|
|
||||||
@ -49,7 +49,7 @@ describe('the validation logic', () => {
|
|||||||
|
|
||||||
## id
|
## id
|
||||||
|
|
||||||
This is suite's unique identifier. This ID is deterministic and will be the same for the same suite across multiple runs. The ID is based on the [project](/advanced/api/test-project) name, module ID and suite order.
|
This is suite's unique identifier. This ID is deterministic and will be the same for the same suite across multiple runs. The ID is based on the [project](/api/advanced/test-project) name, module ID and suite order.
|
||||||
|
|
||||||
The ID looks like this:
|
The ID looks like this:
|
||||||
|
|
||||||
@ -94,7 +94,7 @@ describe('the validation works correctly', () => {
|
|||||||
|
|
||||||
## parent
|
## parent
|
||||||
|
|
||||||
Parent suite. If the suite was called directly inside the [module](/advanced/api/test-module), the parent will be the module itself.
|
Parent suite. If the suite was called directly inside the [module](/api/advanced/test-module), the parent will be the module itself.
|
||||||
|
|
||||||
## options
|
## options
|
||||||
|
|
||||||
@ -114,7 +114,7 @@ The options that suite was collected with.
|
|||||||
|
|
||||||
## children
|
## children
|
||||||
|
|
||||||
This is a [collection](/advanced/api/test-collection) of all suites and tests inside the current suite.
|
This is a [collection](/api/advanced/test-collection) of all suites and tests inside the current suite.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
for (const task of suite.children) {
|
for (const task of suite.children) {
|
||||||
@ -129,7 +129,7 @@ for (const task of suite.children) {
|
|||||||
```
|
```
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
Note that `suite.children` will only iterate the first level of nesting, it won't go deeper. If you need to iterate over all tests or suites, use [`children.allTests()`](/advanced/api/test-collection#alltests) or [`children.allSuites()`](/advanced/api/test-collection#allsuites). If you need to iterate over everything, use recursive function:
|
Note that `suite.children` will only iterate the first level of nesting, it won't go deeper. If you need to iterate over all tests or suites, use [`children.allTests()`](/api/advanced/test-collection#alltests) or [`children.allSuites()`](/api/advanced/test-collection#allsuites). If you need to iterate over everything, use recursive function:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
function visit(collection: TestCollection) {
|
function visit(collection: TestCollection) {
|
||||||
@ -168,7 +168,7 @@ Checks the running state of the suite. Possible return values:
|
|||||||
- **skipped**: this suite was skipped during collection.
|
- **skipped**: this suite was skipped during collection.
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
Note that [test module](/advanced/api/test-module) also has a `state` method that returns the same values, but it can also return an additional `queued` state if the module wasn't executed yet.
|
Note that [test module](/api/advanced/test-module) also has a `state` method that returns the same values, but it can also return an additional `queued` state if the module wasn't executed yet.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## errors
|
## errors
|
||||||
@ -197,7 +197,7 @@ Note that errors are serialized into simple objects: `instanceof Error` will alw
|
|||||||
function meta(): TaskMeta
|
function meta(): TaskMeta
|
||||||
```
|
```
|
||||||
|
|
||||||
Custom [metadata](/advanced/metadata) that was attached to the suite during its execution or collection. The meta can be attached by assigning a property to the `suite.meta` object during a test run:
|
Custom [metadata](/api/advanced/metadata) that was attached to the suite during its execution or collection. The meta can be attached by assigning a property to the `suite.meta` object during a test run:
|
||||||
|
|
||||||
```ts {7,12}
|
```ts {7,12}
|
||||||
import { test } from 'vitest'
|
import { test } from 'vitest'
|
||||||
@ -53,7 +53,7 @@ This is a global [`ViteDevServer`](https://vite.dev/guide/api-javascript#vitedev
|
|||||||
Public `state` is an experimental API (except `vitest.state.getReportedEntity`). Breaking changes might not follow SemVer, please pin Vitest's version when using it.
|
Public `state` is an experimental API (except `vitest.state.getReportedEntity`). Breaking changes might not follow SemVer, please pin Vitest's version when using it.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
Global state stores information about the current tests. It uses the same API from `@vitest/runner` by default, but we recommend using the [Reported Tasks API](/advanced/reporters#reported-tasks) instead by calling `state.getReportedEntity()` on the `@vitest/runner` API:
|
Global state stores information about the current tests. It uses the same API from `@vitest/runner` by default, but we recommend using the [Reported Tasks API](/api/advanced/reporters#reported-tasks) instead by calling `state.getReportedEntity()` on the `@vitest/runner` API:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const task = vitest.state.idMap.get(taskId) // old API
|
const task = vitest.state.idMap.get(taskId) // old API
|
||||||
@ -78,7 +78,7 @@ The instance of a Vitest watcher with useful methods to track file changes and r
|
|||||||
|
|
||||||
## projects
|
## projects
|
||||||
|
|
||||||
An array of [test projects](/advanced/api/test-project) that belong to user's projects. If the user did not specify a them, this array will only contain a [root project](#getrootproject).
|
An array of [test projects](/api/advanced/test-project) that belong to user's projects. If the user did not specify a them, this array will only contain a [root project](#getrootproject).
|
||||||
|
|
||||||
Vitest will ensure that there is always at least one project in this array. If the user specifies a non-existent `--project` name, Vitest will throw an error before this array is defined.
|
Vitest will ensure that there is always at least one project in this array. If the user specifies a non-existent `--project` name, Vitest will throw an error before this array is defined.
|
||||||
|
|
||||||
@ -132,7 +132,7 @@ declare module 'vitest' {
|
|||||||
```
|
```
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
Technically, `provide` is a method of [`TestProject`](/advanced/api/test-project), so it is limited to the specific project. However, all projects inherit the values from the root project which makes `vitest.provide` universal way of passing down values to tests.
|
Technically, `provide` is a method of [`TestProject`](/api/advanced/test-project), so it is limited to the specific project. However, all projects inherit the values from the root project which makes `vitest.provide` universal way of passing down values to tests.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## getProvidedContext
|
## getProvidedContext
|
||||||
@ -165,7 +165,7 @@ function globTestSpecifications(
|
|||||||
): Promise<TestSpecification[]>
|
): Promise<TestSpecification[]>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method constructs new [test specifications](/advanced/api/test-specification) by collecting every test in all projects with [`project.globTestFiles`](/advanced/api/test-project#globtestfiles). It accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli).
|
This method constructs new [test specifications](/api/advanced/test-specification) by collecting every test in all projects with [`project.globTestFiles`](/api/advanced/test-project#globtestfiles). It accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli).
|
||||||
|
|
||||||
This method automatically caches all test specifications. When you call [`getModuleSpecifications`](#getmodulespecifications) next time, it will return the same specifications unless [`clearSpecificationsCache`](#clearspecificationscache) was called before that.
|
This method automatically caches all test specifications. When you call [`getModuleSpecifications`](#getmodulespecifications) next time, it will return the same specifications unless [`clearSpecificationsCache`](#clearspecificationscache) was called before that.
|
||||||
|
|
||||||
@ -187,7 +187,7 @@ function getRelevantTestSpecifications(
|
|||||||
): Promise<TestSpecification[]>
|
): Promise<TestSpecification[]>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method resolves every test specification by calling [`project.globTestFiles`](/advanced/api/test-project#globtestfiles). It accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli). If `--changed` flag was specified, the list will be filtered to include only files that changed. `getRelevantTestSpecifications` doesn't run any test files.
|
This method resolves every test specification by calling [`project.globTestFiles`](/api/advanced/test-project#globtestfiles). It accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli). If `--changed` flag was specified, the list will be filtered to include only files that changed. `getRelevantTestSpecifications` doesn't run any test files.
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
This method can be slow because it needs to filter `--changed` flags. Do not use it if you just need a list of test files.
|
This method can be slow because it needs to filter `--changed` flags. Do not use it if you just need a list of test files.
|
||||||
@ -206,7 +206,7 @@ Merge reports from multiple runs located in the specified directory (value from
|
|||||||
|
|
||||||
Note that the `directory` will always be resolved relative to the working directory.
|
Note that the `directory` will always be resolved relative to the working directory.
|
||||||
|
|
||||||
This method is called automatically by [`startVitest`](/advanced/guide/tests) if `config.mergeReports` is set.
|
This method is called automatically by [`startVitest`](/guide/advanced/tests) if `config.mergeReports` is set.
|
||||||
|
|
||||||
## collect
|
## collect
|
||||||
|
|
||||||
@ -214,9 +214,9 @@ This method is called automatically by [`startVitest`](/advanced/guide/tests) if
|
|||||||
function collect(filters?: string[]): Promise<TestRunResult>
|
function collect(filters?: string[]): Promise<TestRunResult>
|
||||||
```
|
```
|
||||||
|
|
||||||
Execute test files without running test callbacks. `collect` returns unhandled errors and an array of [test modules](/advanced/api/test-module). It accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli).
|
Execute test files without running test callbacks. `collect` returns unhandled errors and an array of [test modules](/api/advanced/test-module). It accepts string filters to match the test files - these are the same filters that [CLI supports](/guide/filtering#cli).
|
||||||
|
|
||||||
This method resolves tests specifications based on the config `include`, `exclude`, and `includeSource` values. Read more at [`project.globTestFiles`](/advanced/api/test-project#globtestfiles). If `--changed` flag was specified, the list will be filtered to include only files that changed.
|
This method resolves tests specifications based on the config `include`, `exclude`, and `includeSource` values. Read more at [`project.globTestFiles`](/api/advanced/test-project#globtestfiles). If `--changed` flag was specified, the list will be filtered to include only files that changed.
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
Note that Vitest doesn't use static analysis to collect tests. Vitest will run every test file in isolation, just like it runs regular tests.
|
Note that Vitest doesn't use static analysis to collect tests. Vitest will run every test file in isolation, just like it runs regular tests.
|
||||||
@ -236,7 +236,7 @@ Initialize reporters, the coverage provider, and run tests. This method accepts
|
|||||||
This method should not be called if [`vitest.init()`](#init) is also invoked. Use [`runTestSpecifications`](#runtestspecifications) or [`rerunTestSpecifications`](#reruntestspecifications) instead if you need to run tests after Vitest was initialised.
|
This method should not be called if [`vitest.init()`](#init) is also invoked. Use [`runTestSpecifications`](#runtestspecifications) or [`rerunTestSpecifications`](#reruntestspecifications) instead if you need to run tests after Vitest was initialised.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
This method is called automatically by [`startVitest`](/advanced/guide/tests) if `config.mergeReports` and `config.standalone` are not set.
|
This method is called automatically by [`startVitest`](/guide/advanced/tests) if `config.mergeReports` and `config.standalone` are not set.
|
||||||
|
|
||||||
## init
|
## init
|
||||||
|
|
||||||
@ -252,7 +252,7 @@ Internally, this method is called only if [`--standalone`](/guide/cli#standalone
|
|||||||
This method should not be called if [`vitest.start()`](#start) is also invoked.
|
This method should not be called if [`vitest.start()`](#start) is also invoked.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
This method is called automatically by [`startVitest`](/advanced/guide/tests) if `config.standalone` is set.
|
This method is called automatically by [`startVitest`](/guide/advanced/tests) if `config.standalone` is set.
|
||||||
|
|
||||||
## getModuleSpecifications
|
## getModuleSpecifications
|
||||||
|
|
||||||
@ -262,7 +262,7 @@ function getModuleSpecifications(moduleId: string): TestSpecification[]
|
|||||||
|
|
||||||
Returns a list of test specifications related to the module ID. The ID should already be resolved to an absolute file path. If ID doesn't match `include` or `includeSource` patterns, the returned array will be empty.
|
Returns a list of test specifications related to the module ID. The ID should already be resolved to an absolute file path. If ID doesn't match `include` or `includeSource` patterns, the returned array will be empty.
|
||||||
|
|
||||||
This method can return already cached specifications based on the `moduleId` and `pool`. But note that [`project.createSpecification`](/advanced/api/test-project#createspecification) always returns a new instance and it's not cached automatically. However, specifications are automatically cached when [`runTestSpecifications`](#runtestspecifications) is called.
|
This method can return already cached specifications based on the `moduleId` and `pool`. But note that [`project.createSpecification`](/api/advanced/test-project#createspecification) always returns a new instance and it's not cached automatically. However, specifications are automatically cached when [`runTestSpecifications`](#runtestspecifications) is called.
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
As of Vitest 3, this method uses a cache to check if the file is a test. To make sure that the cache is not empty, call [`globTestSpecifications`](#globtestspecifications) at least once.
|
As of Vitest 3, this method uses a cache to check if the file is a test. To make sure that the cache is not empty, call [`globTestSpecifications`](#globtestspecifications) at least once.
|
||||||
@ -285,7 +285,7 @@ function runTestSpecifications(
|
|||||||
): Promise<TestRunResult>
|
): Promise<TestRunResult>
|
||||||
```
|
```
|
||||||
|
|
||||||
This method runs every test based on the received [specifications](/advanced/api/test-specification). The second argument, `allTestsRun`, is used by the coverage provider to determine if it needs to include uncovered files in report.
|
This method runs every test based on the received [specifications](/api/advanced/test-specification). The second argument, `allTestsRun`, is used by the coverage provider to determine if it needs to include uncovered files in report.
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
This method doesn't trigger `onWatcherRerun`, `onWatcherStart` and `onTestsRerun` callbacks. If you are rerunning tests based on the file change, consider using [`rerunTestSpecifications`](#reruntestspecifications) instead.
|
This method doesn't trigger `onWatcherRerun`, `onWatcherStart` and `onTestsRerun` callbacks. If you are rerunning tests based on the file change, consider using [`rerunTestSpecifications`](#reruntestspecifications) instead.
|
||||||
@ -318,7 +318,7 @@ function collectTests(
|
|||||||
): Promise<TestRunResult>
|
): Promise<TestRunResult>
|
||||||
```
|
```
|
||||||
|
|
||||||
Execute test files without running test callbacks. `collectTests` returns unhandled errors and an array of [test modules](/advanced/api/test-module).
|
Execute test files without running test callbacks. `collectTests` returns unhandled errors and an array of [test modules](/api/advanced/test-module).
|
||||||
|
|
||||||
This method works exactly the same as [`collect`](#collect), but you need to provide test specifications yourself.
|
This method works exactly the same as [`collect`](#collect), but you need to provide test specifications yourself.
|
||||||
|
|
||||||
@ -502,7 +502,7 @@ vitest.onFilterWatchedSpecification(specification =>
|
|||||||
)
|
)
|
||||||
```
|
```
|
||||||
|
|
||||||
Vitest can create different specifications for the same file depending on the `pool` or `locations` options, so do not rely on the reference. Vitest can also return cached specification from [`vitest.getModuleSpecifications`](#getmodulespecifications) - the cache is based on the `moduleId` and `pool`. Note that [`project.createSpecification`](/advanced/api/test-project#createspecification) always returns a new instance.
|
Vitest can create different specifications for the same file depending on the `pool` or `locations` options, so do not rely on the reference. Vitest can also return cached specification from [`vitest.getModuleSpecifications`](#getmodulespecifications) - the cache is based on the `moduleId` and `pool`. Note that [`project.createSpecification`](/api/advanced/test-project#createspecification) always returns a new instance.
|
||||||
|
|
||||||
## matchesProjectFilter <Version>3.1.0</Version> {#matchesprojectfilter}
|
## matchesProjectFilter <Version>3.1.0</Version> {#matchesprojectfilter}
|
||||||
|
|
||||||
@ -300,7 +300,7 @@ await expect.element(
|
|||||||
).toBeVisible()
|
).toBeVisible()
|
||||||
```
|
```
|
||||||
|
|
||||||
## toBeInViewport
|
## toBeInViewport <Version>4.0.0</Version> {#tobeinviewport}
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
function toBeInViewport(options: { ratio?: number }): Promise<void>
|
function toBeInViewport(options: { ratio?: number }): Promise<void>
|
||||||
@ -1082,7 +1082,7 @@ function toMatchScreenshot(
|
|||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
The `toMatchScreenshot` assertion can be configured globally in your
|
The `toMatchScreenshot` assertion can be configured globally in your
|
||||||
[Vitest config](/guide/browser/config#browser-expect-tomatchscreenshot).
|
[Vitest config](/config/browser/expect#tomatchscreenshot).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
This assertion allows you to perform visual regression testing by comparing
|
This assertion allows you to perform visual regression testing by comparing
|
||||||
@ -1194,7 +1194,7 @@ await expect.element(getByTestId('button')).toMatchScreenshot('fancy-button', {
|
|||||||
- `screenshotOptions: object`
|
- `screenshotOptions: object`
|
||||||
|
|
||||||
The same options allowed by
|
The same options allowed by
|
||||||
[`locator.screenshot()`](/guide/browser/locators.html#screenshot), except for:
|
[`locator.screenshot()`](/api/browser/locators.html#screenshot), except for:
|
||||||
|
|
||||||
- `'base64'`
|
- `'base64'`
|
||||||
- `'path'`
|
- `'path'`
|
||||||
@ -61,7 +61,7 @@ CDP session works only with `playwright` provider and only when using `chromium`
|
|||||||
|
|
||||||
## Custom Commands
|
## Custom Commands
|
||||||
|
|
||||||
You can also add your own commands via [`browser.commands`](/guide/browser/config#browser-commands) config option. If you develop a library, you can provide them via a `config` hook inside a plugin:
|
You can also add your own commands via [`browser.commands`](/config/browser/commands) config option. If you develop a library, you can provide them via a `config` hook inside a plugin:
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import type { Plugin } from 'vitest/config'
|
import type { Plugin } from 'vitest/config'
|
||||||
@ -9,7 +9,7 @@ Vitest exposes a context module via `vitest/browser` entry point. As of 2.0, it
|
|||||||
## `userEvent`
|
## `userEvent`
|
||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
The `userEvent` API is explained in detail at [Interactivity API](/guide/browser/interactivity-api).
|
The `userEvent` API is explained in detail at [Interactivity API](/api/browser/interactivity).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@ -43,7 +43,7 @@ export const userEvent: {
|
|||||||
## `commands`
|
## `commands`
|
||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
This API is explained in detail at [Commands API](/guide/browser/commands).
|
This API is explained in detail at [Commands API](/api/browser/commands).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@ -61,7 +61,7 @@ The `page` export provides utilities to interact with the current `page`.
|
|||||||
::: warning
|
::: warning
|
||||||
While it exposes some utilities from Playwright's `page`, it is not the same object. Since the browser context is evaluated in the browser, your tests don't have access to Playwright's `page` because it runs on the server.
|
While it exposes some utilities from Playwright's `page`, it is not the same object. Since the browser context is evaluated in the browser, your tests don't have access to Playwright's `page` because it runs on the server.
|
||||||
|
|
||||||
Use [Commands API](/guide/browser/commands) if you need to have access to Playwright's `page` object.
|
Use [Commands API](/api/browser/commands) if you need to have access to Playwright's `page` object.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
@ -108,7 +108,7 @@ export const page: {
|
|||||||
```
|
```
|
||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
The `getBy*` API is explained at [Locators API](/guide/browser/locators).
|
The `getBy*` API is explained at [Locators API](/api/browser/locators).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
::: warning WARNING <Version>3.2.0</Version>
|
::: warning WARNING <Version>3.2.0</Version>
|
||||||
@ -7,7 +7,7 @@ outline: [2, 3]
|
|||||||
|
|
||||||
A locator is a representation of an element or a number of elements. Every locator is defined by a string called a selector. Vitest abstracts this selector by providing convenient methods that generate them behind the scenes.
|
A locator is a representation of an element or a number of elements. Every locator is defined by a string called a selector. Vitest abstracts this selector by providing convenient methods that generate them behind the scenes.
|
||||||
|
|
||||||
The locator API uses a fork of [Playwright's locators](https://playwright.dev/docs/api/class-locator) called [Ivya](https://npmjs.com/ivya). However, Vitest provides this API to every [provider](/guide/browser/config.html#browser-provider), not just playwright.
|
The locator API uses a fork of [Playwright's locators](https://playwright.dev/docs/api/class-locator) called [Ivya](https://npmjs.com/ivya). However, Vitest provides this API to every [provider](/config/browser#browser-provider), not just playwright.
|
||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
This page covers API usage. To better understand locators and their usage, read [Playwright's "Locators" documentation](https://playwright.dev/docs/locators).
|
This page covers API usage. To better understand locators and their usage, read [Playwright's "Locators" documentation](https://playwright.dev/docs/locators).
|
||||||
@ -368,7 +368,7 @@ page.getByTitle('Create') // ❌
|
|||||||
function getByTestId(text: string | RegExp): Locator
|
function getByTestId(text: string | RegExp): Locator
|
||||||
```
|
```
|
||||||
|
|
||||||
Creates a locator capable of finding an element that matches the specified test id attribute. You can configure the attribute name with [`browser.locators.testIdAttribute`](/guide/browser/config#browser-locators-testidattribute).
|
Creates a locator capable of finding an element that matches the specified test id attribute. You can configure the attribute name with [`browser.locators.testIdAttribute`](/config/browser/locators#testidattribute).
|
||||||
|
|
||||||
```tsx
|
```tsx
|
||||||
<div data-testid="custom-element" />
|
<div data-testid="custom-element" />
|
||||||
@ -614,7 +614,7 @@ import { page } from 'vitest/browser'
|
|||||||
await page.getByRole('img', { name: 'Rose' }).click()
|
await page.getByRole('img', { name: 'Rose' }).click()
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.click`](/guide/browser/interactivity-api#userevent-click)
|
- [See more at `userEvent.click`](/api/browser/interactivity#userevent-click)
|
||||||
|
|
||||||
### dblClick
|
### dblClick
|
||||||
|
|
||||||
@ -630,7 +630,7 @@ import { page } from 'vitest/browser'
|
|||||||
await page.getByRole('img', { name: 'Rose' }).dblClick()
|
await page.getByRole('img', { name: 'Rose' }).dblClick()
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.dblClick`](/guide/browser/interactivity-api#userevent-dblclick)
|
- [See more at `userEvent.dblClick`](/api/browser/interactivity#userevent-dblclick)
|
||||||
|
|
||||||
### tripleClick
|
### tripleClick
|
||||||
|
|
||||||
@ -646,7 +646,7 @@ import { page } from 'vitest/browser'
|
|||||||
await page.getByRole('img', { name: 'Rose' }).tripleClick()
|
await page.getByRole('img', { name: 'Rose' }).tripleClick()
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.tripleClick`](/guide/browser/interactivity-api#userevent-tripleclick)
|
- [See more at `userEvent.tripleClick`](/api/browser/interactivity#userevent-tripleclick)
|
||||||
|
|
||||||
### clear
|
### clear
|
||||||
|
|
||||||
@ -662,7 +662,7 @@ import { page } from 'vitest/browser'
|
|||||||
await page.getByRole('textbox', { name: 'Full Name' }).clear()
|
await page.getByRole('textbox', { name: 'Full Name' }).clear()
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.clear`](/guide/browser/interactivity-api#userevent-clear)
|
- [See more at `userEvent.clear`](/api/browser/interactivity#userevent-clear)
|
||||||
|
|
||||||
### hover
|
### hover
|
||||||
|
|
||||||
@ -678,7 +678,7 @@ import { page } from 'vitest/browser'
|
|||||||
await page.getByRole('img', { name: 'Rose' }).hover()
|
await page.getByRole('img', { name: 'Rose' }).hover()
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.hover`](/guide/browser/interactivity-api#userevent-hover)
|
- [See more at `userEvent.hover`](/api/browser/interactivity#userevent-hover)
|
||||||
|
|
||||||
### unhover
|
### unhover
|
||||||
|
|
||||||
@ -694,7 +694,7 @@ import { page } from 'vitest/browser'
|
|||||||
await page.getByRole('img', { name: 'Rose' }).unhover()
|
await page.getByRole('img', { name: 'Rose' }).unhover()
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.unhover`](/guide/browser/interactivity-api#userevent-unhover)
|
- [See more at `userEvent.unhover`](/api/browser/interactivity#userevent-unhover)
|
||||||
|
|
||||||
### fill
|
### fill
|
||||||
|
|
||||||
@ -710,7 +710,7 @@ import { page } from 'vitest/browser'
|
|||||||
await page.getByRole('input', { name: 'Full Name' }).fill('Mr. Bean')
|
await page.getByRole('input', { name: 'Full Name' }).fill('Mr. Bean')
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.fill`](/guide/browser/interactivity-api#userevent-fill)
|
- [See more at `userEvent.fill`](/api/browser/interactivity#userevent-fill)
|
||||||
|
|
||||||
### dropTo
|
### dropTo
|
||||||
|
|
||||||
@ -732,7 +732,7 @@ const france = page.getByText('France')
|
|||||||
await paris.dropTo(france)
|
await paris.dropTo(france)
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.dragAndDrop`](/guide/browser/interactivity-api#userevent-draganddrop)
|
- [See more at `userEvent.dragAndDrop`](/api/browser/interactivity#userevent-draganddrop)
|
||||||
|
|
||||||
### selectOptions
|
### selectOptions
|
||||||
|
|
||||||
@ -764,7 +764,7 @@ await languages.selectOptions([
|
|||||||
])
|
])
|
||||||
```
|
```
|
||||||
|
|
||||||
- [See more at `userEvent.selectOptions`](/guide/browser/interactivity-api#userevent-selectoptions)
|
- [See more at `userEvent.selectOptions`](/api/browser/interactivity#userevent-selectoptions)
|
||||||
|
|
||||||
### screenshot
|
### screenshot
|
||||||
|
|
||||||
@ -779,7 +779,7 @@ function screenshot(options?: LocatorScreenshotOptions & { base64?: false }): Pr
|
|||||||
|
|
||||||
Creates a screenshot of the element matching the locator's selector.
|
Creates a screenshot of the element matching the locator's selector.
|
||||||
|
|
||||||
You can specify the save location for the screenshot using the `path` option, which is relative to the current test file. If the `path` option is not set, Vitest will default to using [`browser.screenshotDirectory`](/guide/browser/config#browser-screenshotdirectory) (`__screenshot__` by default), along with the names of the file and the test to determine the screenshot's filepath.
|
You can specify the save location for the screenshot using the `path` option, which is relative to the current test file. If the `path` option is not set, Vitest will default to using [`browser.screenshotDirectory`](/config/browser/screenshotdirectory) (`__screenshot__` by default), along with the names of the file and the test to determine the screenshot's filepath.
|
||||||
|
|
||||||
If you also need the content of the screenshot, you can specify `base64: true` to return it alongside the filepath where the screenshot is saved.
|
If you also need the content of the screenshot, you can specify `base64: true` to return it alongside the filepath where the screenshot is saved.
|
||||||
|
|
||||||
@ -850,7 +850,7 @@ If _no element_ matches the selector, an error is thrown. Consider using [`.quer
|
|||||||
If _multiple elements_ match the selector, an error is thrown. Use [`.elements()`](#elements) when you need all matching DOM Elements or [`.all()`](#all) if you need an array of locators matching the selector.
|
If _multiple elements_ match the selector, an error is thrown. Use [`.elements()`](#elements) when you need all matching DOM Elements or [`.all()`](#all) if you need an array of locators matching the selector.
|
||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
This method can be useful if you need to pass it down to an external library. It is called automatically when locator is used with `expect.element` every time the assertion is [retried](/guide/browser/assertion-api):
|
This method can be useful if you need to pass it down to an external library. It is called automatically when locator is used with `expect.element` every time the assertion is [retried](/api/browser/assertions):
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
await expect.element(page.getByRole('button')).toBeDisabled()
|
await expect.element(page.getByRole('button')).toBeDisabled()
|
||||||
@ -920,7 +920,7 @@ function all(): Locator[]
|
|||||||
|
|
||||||
This method returns an array of new locators that match the selector.
|
This method returns an array of new locators that match the selector.
|
||||||
|
|
||||||
Internally, this method calls `.elements` and wraps every element using [`page.elementLocator`](/guide/browser/context#page).
|
Internally, this method calls `.elements` and wraps every element using [`page.elementLocator`](/api/browser/context#page).
|
||||||
|
|
||||||
- [See `locator.elements()`](#elements)
|
- [See `locator.elements()`](#elements)
|
||||||
|
|
||||||
@ -429,8 +429,6 @@ You can also access Object attributes with `.`, if you are using objects as argu
|
|||||||
// ✓ add(3, b) -> 3b
|
// ✓ add(3, b) -> 3b
|
||||||
```
|
```
|
||||||
|
|
||||||
Starting from Vitest 0.25.3, you can also use template string table.
|
|
||||||
|
|
||||||
* First row should be column names, separated by `|`;
|
* First row should be column names, separated by `|`;
|
||||||
* One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax.
|
* One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax.
|
||||||
|
|
||||||
@ -1041,8 +1039,6 @@ describe.each([
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
Starting from Vitest 0.25.3, you can also use template string table.
|
|
||||||
|
|
||||||
* First row should be column names, separated by `|`;
|
* First row should be column names, separated by `|`;
|
||||||
* One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax.
|
* One or more subsequent rows of data supplied as template literal expressions using `${value}` syntax.
|
||||||
|
|
||||||
@ -1159,7 +1155,7 @@ afterEach(async () => {
|
|||||||
Here, the `afterEach` ensures that testing data is cleared after each test runs.
|
Here, the `afterEach` ensures that testing data is cleared after each test runs.
|
||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
Vitest 1.3.0 added [`onTestFinished`](#ontestfinished) hook. You can call it during the test execution to cleanup any state after the test has finished running.
|
You can also use [`onTestFinished`](#ontestfinished) during the test execution to cleanup any state after the test has finished running.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
### beforeAll
|
### beforeAll
|
||||||
|
|||||||
@ -850,7 +850,7 @@ await vi.advanceTimersToNextTimerAsync() // log: 3
|
|||||||
function advanceTimersToNextFrame(): Vitest
|
function advanceTimersToNextFrame(): Vitest
|
||||||
```
|
```
|
||||||
|
|
||||||
Similar to [`vi.advanceTimersByTime`](https://vitest.dev/api/vi#vi-advancetimersbytime), but will advance timers by the milliseconds needed to execute callbacks currently scheduled with `requestAnimationFrame`.
|
Similar to [`vi.advanceTimersByTime`](/api/vi#vi-advancetimersbytime), but will advance timers by the milliseconds needed to execute callbacks currently scheduled with `requestAnimationFrame`.
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
let frameRendered = false
|
let frameRendered = false
|
||||||
|
|||||||
@ -110,7 +110,7 @@ export default defineConfig({
|
|||||||
|
|
||||||
## Custom Browser Locators API
|
## Custom Browser Locators API
|
||||||
|
|
||||||
Built-in locators might not be enough to express your application’s needs. Instead of falling back to CSS and losing the retry-ability protection that Vitest provides through its locator API, we now recommend extending locators using the new [`locators.extend` API](/guide/browser/locators#custom-locators).
|
Built-in locators might not be enough to express your application’s needs. Instead of falling back to CSS and losing the retry-ability protection that Vitest provides through its locator API, we now recommend extending locators using the new [`locators.extend` API](/api/browser/locators#custom-locators).
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { locators } from '@vitest/browser/context'
|
import { locators } from '@vitest/browser/context'
|
||||||
@ -172,7 +172,7 @@ locators.extend({
|
|||||||
await page.getByRole('textbox').clickAndFill('Hello World')
|
await page.getByRole('textbox').clickAndFill('Hello World')
|
||||||
```
|
```
|
||||||
|
|
||||||
Please, refer to the [`locators.extend` API](/guide/browser/locators#custom-locators) for more information.
|
Please, refer to the [`locators.extend` API](/api/browser/locators#custom-locators) for more information.
|
||||||
|
|
||||||
## Explicit Resource Management in `vi.spyOn` and `vi.fn`
|
## Explicit Resource Management in `vi.spyOn` and `vi.fn`
|
||||||
|
|
||||||
|
|||||||
@ -62,7 +62,7 @@ For the latest news about the Vitest ecosystem and Vitest core, follow us on [Bl
|
|||||||
</video>
|
</video>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
Alongside this change, we also redesign the public reporter API (the `reporters` field) making the [lifecycle](/advanced/api/reporters) easier to understand.
|
Alongside this change, we also redesign the public reporter API (the `reporters` field) making the [lifecycle](/api/advanced/reporters) easier to understand.
|
||||||
|
|
||||||
You can follow the design process in [#7069](https://github.com/vitest-dev/vitest/pull/7069) PR. It was a hard fight trying to reverse-engineer the previous `onTaskUpdate` API to make this new elegant lifecycle possible.
|
You can follow the design process in [#7069](https://github.com/vitest-dev/vitest/pull/7069) PR. It was a hard fight trying to reverse-engineer the previous `onTaskUpdate` API to make this new elegant lifecycle possible.
|
||||||
|
|
||||||
@ -115,7 +115,7 @@ export default defineConfig({
|
|||||||
|
|
||||||
The main advantage of `instances` over `workspace` is a better caching strategy - Vitest creates only a single Vite server to serve files, which are processed only once, independent of how many browsers you test.
|
The main advantage of `instances` over `workspace` is a better caching strategy - Vitest creates only a single Vite server to serve files, which are processed only once, independent of how many browsers you test.
|
||||||
|
|
||||||
This release also improves the documentation of Browser Mode features and introduces separate guides for [Playwright](/guide/browser/playwright) and [WebdriverIO](/guide/browser/webdriverio) hopefully making it easier to configure.
|
This release also improves the documentation of Browser Mode features and introduces separate guides for [Playwright](/config/browser/playwright) and [WebdriverIO](/config/browser/webdriverio) hopefully making it easier to configure.
|
||||||
|
|
||||||
## Filtering by Location
|
## Filtering by Location
|
||||||
|
|
||||||
|
|||||||
@ -147,7 +147,7 @@ With these changes, the `@vitest/browser` package can be removed from your depen
|
|||||||
Vitest 4 adds support for [Visual Regression testing](/guide/browser/visual-regression-testing.md) in Browser Mode. We will continue to iterate on this feature to improve the experience.
|
Vitest 4 adds support for [Visual Regression testing](/guide/browser/visual-regression-testing.md) in Browser Mode. We will continue to iterate on this feature to improve the experience.
|
||||||
|
|
||||||
Visual regression testing in Vitest can be done through the
|
Visual regression testing in Vitest can be done through the
|
||||||
[`toMatchScreenshot` assertion](/guide/browser/assertion-api.html#tomatchscreenshot):
|
[`toMatchScreenshot` assertion](/api/browser/assertions.html#tomatchscreenshot):
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
import { expect, test } from 'vitest'
|
import { expect, test } from 'vitest'
|
||||||
@ -175,7 +175,7 @@ await expect.element(page.getByText('To')).toBeInViewport({ ratio: 0.5 })
|
|||||||
|
|
||||||
## Playwright Traces Support
|
## Playwright Traces Support
|
||||||
|
|
||||||
Vitest 4 supports generating [Playwright Traces](/guide/browser/trace-view). To enable tracing, you need to set the [`trace`](/guide/browser/config#browser-trace) option in the `test.browser` configuration or pass down `--browser.trace=on` option (`off`, `on-first-retry`, `on-all-retries`, `retain-on-failure` are also available).
|
Vitest 4 supports generating [Playwright Traces](/guide/browser/trace-view). To enable tracing, you need to set the [`trace`](/config/browser/trace) option in the `test.browser` configuration or pass down `--browser.trace=on` option (`off`, `on-first-retry`, `on-all-retries`, `retain-on-failure` are also available).
|
||||||
|
|
||||||

|

|
||||||
|
|
||||||
@ -184,7 +184,7 @@ The traces are available in reporters as [annotations](/guide/test-annotations).
|
|||||||
## Locator Improvements
|
## Locator Improvements
|
||||||
|
|
||||||
The `frameLocator` method returns a `FrameLocator` instance that can be used to find elements inside the iframe.
|
The `frameLocator` method returns a `FrameLocator` instance that can be used to find elements inside the iframe.
|
||||||
Vitest now supports a new [`page.frameLocator`](/guide/browser/context#framelocator) API (only with `playwright` provider).
|
Vitest now supports a new [`page.frameLocator`](/api/browser/context#framelocator) API (only with `playwright` provider).
|
||||||
|
|
||||||
```ts
|
```ts
|
||||||
const frame = page.frameLocator(
|
const frame = page.frameLocator(
|
||||||
@ -205,7 +205,7 @@ await expect.element(page.getByText('Item')).toHaveLength(3)
|
|||||||
|
|
||||||
The [vscode extension](https://vitest.dev/vscode) now supports "Debug Test" button when running browser tests.
|
The [vscode extension](https://vitest.dev/vscode) now supports "Debug Test" button when running browser tests.
|
||||||
|
|
||||||
If you prefer configuring the debug options yourself, you can start Vitest with the `--inspect` flag (available with `playwright` and `webdriverio`) and connect to [DevTools](chrome://inspect/) manually. In this case Vitest will also disable the new [`trackUnhandledErrors`](/guide/browser/config#browser-trackunhandlederrors) option automatically.
|
If you prefer configuring the debug options yourself, you can start Vitest with the `--inspect` flag (available with `playwright` and `webdriverio`) and connect to [DevTools](chrome://inspect/) manually. In this case Vitest will also disable the new [`trackUnhandledErrors`](/config/browser/trackunhandlederrors) option automatically.
|
||||||
|
|
||||||
## Type-Aware Hooks
|
## Type-Aware Hooks
|
||||||
|
|
||||||
@ -318,14 +318,14 @@ export default defineConfig({
|
|||||||
|
|
||||||
## New API Methods
|
## New API Methods
|
||||||
|
|
||||||
Vitest 4 comes with new advanced public [API methods](/advanced/api/vitest):
|
Vitest 4 comes with new advanced public [API methods](/api/advanced/vitest):
|
||||||
|
|
||||||
- [`experimental_parseSpecifications`](/advanced/api/vitest#parsespecification) allows you to parse a test file without running it.
|
- [`experimental_parseSpecifications`](/api/advanced/vitest#parsespecification) allows you to parse a test file without running it.
|
||||||
- [`watcher`](/advanced/api/vitest#watcher) exposes methods that can be used when you disable the default Vitest watcher.
|
- [`watcher`](/api/advanced/vitest#watcher) exposes methods that can be used when you disable the default Vitest watcher.
|
||||||
- [`enableCoverage`](/advanced/api/vitest#enablecoverage) and [`disableCoverage`](/advanced/api/vitest#disablecoverage) allow you to enable and disable coverage dynamically.
|
- [`enableCoverage`](/api/advanced/vitest#enablecoverage) and [`disableCoverage`](/api/advanced/vitest#disablecoverage) allow you to enable and disable coverage dynamically.
|
||||||
- [`getSeed`](/advanced/api/vitest#enablecoverage) returns the seed value, if tests run at random.
|
- [`getSeed`](/api/advanced/vitest#enablecoverage) returns the seed value, if tests run at random.
|
||||||
- [`getGlobalTestNamePattern`](/advanced/api/vitest#getglobaltestnamepattern) returns the current test name pattern.
|
- [`getGlobalTestNamePattern`](/api/advanced/vitest#getglobaltestnamepattern) returns the current test name pattern.
|
||||||
- [`waitForTestRunEnd`](/advanced/api/vitest#waitfortestrunend) returns a promise that resolves when all tests have finished running.
|
- [`waitForTestRunEnd`](/api/advanced/vitest#waitfortestrunend) returns a promise that resolves when all tests have finished running.
|
||||||
|
|
||||||
## Breaking changes
|
## Breaking changes
|
||||||
|
|
||||||
|
|||||||
18
docs/config/alias.md
Normal file
18
docs/config/alias.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
title: alias | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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`.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
Vitest uses Vite SSR primitives to run tests which has [certain pitfalls](https://vitejs.dev/guide/ssr.html#ssr-externals).
|
||||||
|
|
||||||
|
1. Aliases affect only modules imported directly with an `import` keyword by an [inlined](#server-deps-inline) module (all source code is inlined by default).
|
||||||
|
2. Vitest does not support aliasing `require` calls.
|
||||||
|
3. If you are aliasing an external dependency (e.g., `react` -> `preact`), you may want to alias the actual `node_modules` packages instead to make it work for externalized dependencies. Both [Yarn](https://classic.yarnpkg.com/en/docs/cli/add/#toc-yarn-add-alias) and [pnpm](https://pnpm.io/aliases/) support aliasing via the `npm:` prefix.
|
||||||
|
:::
|
||||||
37
docs/config/allowonly.md
Normal file
37
docs/config/allowonly.md
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
title: allowOnly | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# allowOnly
|
||||||
|
|
||||||
|
- **Type**: `boolean`
|
||||||
|
- **Default**: `!process.env.CI`
|
||||||
|
- **CLI:** `--allowOnly`, `--allowOnly=false`
|
||||||
|
|
||||||
|
By default, Vitest does not permit tests marked with the [`only`](/api/#test-only) flag in Continuous Integration (CI) environments. Conversely, in local development environments, Vitest allows these tests to run.
|
||||||
|
|
||||||
|
::: info
|
||||||
|
Vitest uses [`std-env`](https://www.npmjs.com/package/std-env) package to detect the environment.
|
||||||
|
:::
|
||||||
|
|
||||||
|
You can customize this behavior by explicitly setting the `allowOnly` option to either `true` or `false`.
|
||||||
|
|
||||||
|
::: code-group
|
||||||
|
```js [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
allowOnly: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
```bash [CLI]
|
||||||
|
vitest --allowOnly
|
||||||
|
```
|
||||||
|
:::
|
||||||
|
|
||||||
|
When enabled, Vitest will not fail the test suite if tests marked with [`only`](/api/#test-only) are detected, including in CI environments.
|
||||||
|
|
||||||
|
When disabled, Vitest will fail the test suite if tests marked with [`only`](/api/#test-only) are detected, including in local development environments.
|
||||||
12
docs/config/api.md
Normal file
12
docs/config/api.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: api | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# api
|
||||||
|
|
||||||
|
- **Type:** `boolean | number`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **CLI:** `--api`, `--api.port`, `--api.host`, `--api.strictPort`
|
||||||
|
|
||||||
|
Listen to port and serve API for [the UI](/guide/ui) or [browser server](/guide/browser/). When set to `true`, the default port is `51204`.
|
||||||
11
docs/config/attachmentsdir.md
Normal file
11
docs/config/attachmentsdir.md
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
title: attachmentsDir | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# attachmentsDir
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **Default:** `'.vitest-attachments'`
|
||||||
|
|
||||||
|
Directory path for storing attachments created by [`context.annotate`](/guide/test-context#annotate) relative to the project root.
|
||||||
14
docs/config/bail.md
Normal file
14
docs/config/bail.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
---
|
||||||
|
title: bail | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# bail
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `0`
|
||||||
|
- **CLI**: `--bail=<value>`
|
||||||
|
|
||||||
|
Stop test execution when given number of tests have failed.
|
||||||
|
|
||||||
|
By default Vitest will run all of your test cases even if some of them fail. This may not be desired for CI builds where you are only interested in 100% successful builds and would like to stop test execution as early as possible when test failures occur. The `bail` option can be used to speed up CI runs by preventing it from running more tests when failures have occurred.
|
||||||
70
docs/config/benchmark.md
Normal file
70
docs/config/benchmark.md
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
---
|
||||||
|
title: benchmark | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# benchmark <Experimental /> {#benchmark}
|
||||||
|
|
||||||
|
- **Type:** `{ include?, exclude?, ... }`
|
||||||
|
|
||||||
|
Options used when running `vitest bench`.
|
||||||
|
|
||||||
|
## benchmark.include
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** `['**/*.{bench,benchmark}.?(c|m)[jt]s?(x)']`
|
||||||
|
|
||||||
|
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
|
||||||
|
|
||||||
|
Deprecated in favor of `benchmark.outputJson`.
|
||||||
|
|
||||||
|
## benchmark.outputJson {#benchmark-outputJson}
|
||||||
|
|
||||||
|
- **Type:** `string | undefined`
|
||||||
|
- **Default:** `undefined`
|
||||||
|
|
||||||
|
A file path to store the benchmark result, which can be used for `--compare` option later.
|
||||||
|
|
||||||
|
For example:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
# save main branch's result
|
||||||
|
git checkout main
|
||||||
|
vitest bench --outputJson main.json
|
||||||
|
|
||||||
|
# change a branch and compare against main
|
||||||
|
git checkout feature
|
||||||
|
vitest bench --compare main.json
|
||||||
|
```
|
||||||
|
|
||||||
|
## benchmark.compare {#benchmark-compare}
|
||||||
|
|
||||||
|
- **Type:** `string | undefined`
|
||||||
|
- **Default:** `undefined`
|
||||||
|
|
||||||
|
A file path to a previous benchmark result to compare against current runs.
|
||||||
@ -1,3 +1,8 @@
|
|||||||
|
---
|
||||||
|
title: Browser Config Reference | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
# Browser Config Reference
|
# Browser Config Reference
|
||||||
|
|
||||||
You can change the browser configuration by updating the `test.browser` field in your [config file](/config/). An example of a simple config file:
|
You can change the browser configuration by updating the `test.browser` field in your [config file](/config/). An example of a simple config file:
|
||||||
@ -51,7 +56,7 @@ Run all tests inside a browser by default. Note that `--browser` only works if y
|
|||||||
|
|
||||||
Defines multiple browser setups. Every config has to have at least a `browser` field.
|
Defines multiple browser setups. Every config has to have at least a `browser` field.
|
||||||
|
|
||||||
You can specify most of the [project options](/config/) (not marked with a <NonProjectOption /> icon) and some of the `browser` options like `browser.testerHtmlPath`.
|
You can specify most of the [project options](/config/) (not marked with a <CRoot /> icon) and some of the `browser` options like `browser.testerHtmlPath`.
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
Every browser config inherits options from the root config:
|
Every browser config inherits options from the root config:
|
||||||
@ -89,7 +94,7 @@ List of available `browser` options:
|
|||||||
- [`browser.screenshotFailures`](#browser-screenshotfailures)
|
- [`browser.screenshotFailures`](#browser-screenshotfailures)
|
||||||
- [`browser.provider`](#browser-provider)
|
- [`browser.provider`](#browser-provider)
|
||||||
|
|
||||||
Under the hood, Vitest transforms these instances into separate [test projects](/advanced/api/test-project) sharing a single Vite server for better caching performance.
|
Under the hood, Vitest transforms these instances into separate [test projects](/api/advanced/test-project) sharing a single Vite server for better caching performance.
|
||||||
|
|
||||||
## browser.headless
|
## browser.headless
|
||||||
|
|
||||||
@ -224,7 +229,7 @@ Default iframe's viewport.
|
|||||||
|
|
||||||
## browser.locators
|
## browser.locators
|
||||||
|
|
||||||
Options for built-in [browser locators](/guide/browser/locators).
|
Options for built-in [browser locators](/api/browser/locators).
|
||||||
|
|
||||||
### browser.locators.testIdAttribute
|
### browser.locators.testIdAttribute
|
||||||
|
|
||||||
@ -292,7 +297,7 @@ export interface BrowserScript {
|
|||||||
- **Type:** `Record<string, BrowserCommand>`
|
- **Type:** `Record<string, BrowserCommand>`
|
||||||
- **Default:** `{ readFile, writeFile, ... }`
|
- **Default:** `{ readFile, writeFile, ... }`
|
||||||
|
|
||||||
Custom [commands](/guide/browser/commands) that can be imported during browser tests from `vitest/browser`.
|
Custom [commands](/api/browser/commands) that can be imported during browser tests from `vitest/browser`.
|
||||||
|
|
||||||
## browser.connectTimeout
|
## browser.connectTimeout
|
||||||
|
|
||||||
@ -346,7 +351,7 @@ interface TraceOptions {
|
|||||||
```
|
```
|
||||||
|
|
||||||
::: danger WARNING
|
::: danger WARNING
|
||||||
This option is supported only by the [**playwright**](/guide/browser/playwright) provider.
|
This option is supported only by the [**playwright**](/config/browser/playwright) provider.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## browser.trackUnhandledErrors
|
## browser.trackUnhandledErrors
|
||||||
@ -367,7 +372,7 @@ Disabling this will completely remove all Vitest error handlers, which can help
|
|||||||
### browser.expect.toMatchScreenshot
|
### browser.expect.toMatchScreenshot
|
||||||
|
|
||||||
Default options for the
|
Default options for the
|
||||||
[`toMatchScreenshot` assertion](/guide/browser/assertion-api.html#tomatchscreenshot).
|
[`toMatchScreenshot` assertion](/api/browser/assertions.html#tomatchscreenshot).
|
||||||
These options will be applied to all screenshot assertions.
|
These options will be applied to all screenshot assertions.
|
||||||
|
|
||||||
::: tip
|
::: tip
|
||||||
@ -399,7 +404,7 @@ export default defineConfig({
|
|||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|
||||||
[All options available in the `toMatchScreenshot` assertion](/guide/browser/assertion-api#options)
|
[All options available in the `toMatchScreenshot` assertion](/api/browser/assertions#options)
|
||||||
can be configured here. Additionally, two path resolution functions are
|
can be configured here. Additionally, two path resolution functions are
|
||||||
available: `resolveScreenshotPath` and `resolveDiffPath`.
|
available: `resolveScreenshotPath` and `resolveDiffPath`.
|
||||||
|
|
||||||
@ -450,7 +455,7 @@ receives an object with the following properties:
|
|||||||
- `screenshotDirectory: string`
|
- `screenshotDirectory: string`
|
||||||
|
|
||||||
The value provided to
|
The value provided to
|
||||||
[`browser.screenshotDirectory`](/guide/browser/config#browser-screenshotdirectory),
|
[`browser.screenshotDirectory`](/config/browser/screenshotdirectory),
|
||||||
if none is provided, its default value.
|
if none is provided, its default value.
|
||||||
|
|
||||||
- `root: string`
|
- `root: string`
|
||||||
12
docs/config/browser/api.md
Normal file
12
docs/config/browser/api.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: browser.api | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.api
|
||||||
|
|
||||||
|
- **Type:** `number | { port?, strictPort?, host? }`
|
||||||
|
- **Default:** `63315`
|
||||||
|
- **CLI:** `--browser.api=63315`, `--browser.api.port=1234, --browser.api.host=example.com`
|
||||||
|
|
||||||
|
Configure options for Vite server that serves code in the browser. Does not affect [`test.api`](#api) option. By default, Vitest assigns port `63315` to avoid conflicts with the development server, allowing you to run both in parallel.
|
||||||
11
docs/config/browser/commands.md
Normal file
11
docs/config/browser/commands.md
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
title: browser.commands | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.commands
|
||||||
|
|
||||||
|
- **Type:** `Record<string, BrowserCommand>`
|
||||||
|
- **Default:** `{ readFile, writeFile, ... }`
|
||||||
|
|
||||||
|
Custom [commands](/api/browser/commands) that can be imported during browser tests from `vitest/browser`.
|
||||||
15
docs/config/browser/connecttimeout.md
Normal file
15
docs/config/browser/connecttimeout.md
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
title: browser.connectTimeout | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.connectTimeout
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `60_000`
|
||||||
|
|
||||||
|
The timeout in milliseconds. If connection to the browser takes longer, the test suite will fail.
|
||||||
|
|
||||||
|
::: info
|
||||||
|
This is the time it should take for the browser to establish the WebSocket connection with the Vitest server. In normal circumstances, this timeout should never be reached.
|
||||||
|
:::
|
||||||
44
docs/config/browser/enabled.md
Normal file
44
docs/config/browser/enabled.md
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
title: browser.enabled | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.enabled
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **CLI:** `--browser`, `--browser.enabled=false`
|
||||||
|
|
||||||
|
Enabling this flag makes Vitest run all tests in a [browser](/guide/browser/) by default. If you are configuring other browser options via the CLI, you can use `--browser.enabled` alongside them instead of `--browser`:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
vitest --browser.enabled --browser.headless
|
||||||
|
```
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
To enable [Browser Mode](/guide/browser/), you must also specify the [`provider`](/config/browser/provider) and at least one [`instance`](/config/browser/instances). Available providers:
|
||||||
|
|
||||||
|
- [playwright](/config/browser/playwright)
|
||||||
|
- [webdriverio](/config/browser/webdriverio)
|
||||||
|
- [preview](/config/browser/preview)
|
||||||
|
:::
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```js{7} [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
import { playwright } from '@vitest/browser-playwright'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
browser: {
|
||||||
|
enabled: true,
|
||||||
|
provider: playwright(),
|
||||||
|
instances: [
|
||||||
|
{ browser: 'chromium' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
If you use TypeScript, the `browser` field in `instances` provides autocompletion based on your provider.
|
||||||
255
docs/config/browser/expect.md
Normal file
255
docs/config/browser/expect.md
Normal file
@ -0,0 +1,255 @@
|
|||||||
|
---
|
||||||
|
title: browser.expect | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.expect
|
||||||
|
|
||||||
|
- **Type:** `ExpectOptions`
|
||||||
|
|
||||||
|
## browser.expect.toMatchScreenshot
|
||||||
|
|
||||||
|
Default options for the
|
||||||
|
[`toMatchScreenshot` assertion](/api/browser/assertions.html#tomatchscreenshot).
|
||||||
|
These options will be applied to all screenshot assertions.
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
Setting global defaults for screenshot assertions helps maintain consistency
|
||||||
|
across your test suite and reduces repetition in individual tests. You can still
|
||||||
|
override these defaults at the assertion level when needed for specific test cases.
|
||||||
|
:::
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
browser: {
|
||||||
|
enabled: true,
|
||||||
|
expect: {
|
||||||
|
toMatchScreenshot: {
|
||||||
|
comparatorName: 'pixelmatch',
|
||||||
|
comparatorOptions: {
|
||||||
|
threshold: 0.2,
|
||||||
|
allowedMismatchedPixels: 100,
|
||||||
|
},
|
||||||
|
resolveScreenshotPath: ({ arg, browserName, ext, testFileName }) =>
|
||||||
|
`custom-screenshots/${testFileName}/${arg}-${browserName}${ext}`,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
[All options available in the `toMatchScreenshot` assertion](/api/browser/assertions#options)
|
||||||
|
can be configured here. Additionally, two path resolution functions are
|
||||||
|
available: `resolveScreenshotPath` and `resolveDiffPath`.
|
||||||
|
|
||||||
|
## browser.expect.toMatchScreenshot.resolveScreenshotPath
|
||||||
|
|
||||||
|
- **Type:** `(data: PathResolveData) => string`
|
||||||
|
- **Default output:** `` `${root}/${testFileDirectory}/${screenshotDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}` ``
|
||||||
|
|
||||||
|
A function to customize where reference screenshots are stored. The function
|
||||||
|
receives an object with the following properties:
|
||||||
|
|
||||||
|
- `arg: string`
|
||||||
|
|
||||||
|
Path **without** extension, sanitized and relative to the test file.
|
||||||
|
|
||||||
|
This comes from the arguments passed to `toMatchScreenshot`; if called
|
||||||
|
without arguments this will be the auto-generated name.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
test('calls `onClick`', () => {
|
||||||
|
expect(locator).toMatchScreenshot()
|
||||||
|
// arg = "calls-onclick-1"
|
||||||
|
})
|
||||||
|
|
||||||
|
expect(locator).toMatchScreenshot('foo/bar/baz.png')
|
||||||
|
// arg = "foo/bar/baz"
|
||||||
|
|
||||||
|
expect(locator).toMatchScreenshot('../foo/bar/baz.png')
|
||||||
|
// arg = "foo/bar/baz"
|
||||||
|
```
|
||||||
|
|
||||||
|
- `ext: string`
|
||||||
|
|
||||||
|
Screenshot extension, with leading dot.
|
||||||
|
|
||||||
|
This can be set through the arguments passed to `toMatchScreenshot`, but
|
||||||
|
the value will fall back to `'.png'` if an unsupported extension is used.
|
||||||
|
|
||||||
|
- `browserName: string`
|
||||||
|
|
||||||
|
The instance's browser name.
|
||||||
|
|
||||||
|
- `platform: NodeJS.Platform`
|
||||||
|
|
||||||
|
The value of
|
||||||
|
[`process.platform`](https://nodejs.org/docs/v22.16.0/api/process.html#processplatform).
|
||||||
|
|
||||||
|
- `screenshotDirectory: string`
|
||||||
|
|
||||||
|
The value provided to
|
||||||
|
[`browser.screenshotDirectory`](/config/browser/screenshotdirectory),
|
||||||
|
if none is provided, its default value.
|
||||||
|
|
||||||
|
- `root: string`
|
||||||
|
|
||||||
|
Absolute path to the project's [`root`](/config/#root).
|
||||||
|
|
||||||
|
- `testFileDirectory: string`
|
||||||
|
|
||||||
|
Path to the test file, relative to the project's [`root`](/config/#root).
|
||||||
|
|
||||||
|
- `testFileName: string`
|
||||||
|
|
||||||
|
The test's filename.
|
||||||
|
|
||||||
|
- `testName: string`
|
||||||
|
|
||||||
|
The [`test`](/api/#test)'s name, including parent
|
||||||
|
[`describe`](/api/#describe), sanitized.
|
||||||
|
|
||||||
|
- `attachmentsDir: string`
|
||||||
|
|
||||||
|
The value provided to [`attachmentsDir`](/config/#attachmentsdir), if none is
|
||||||
|
provided, its default value.
|
||||||
|
|
||||||
|
For example, to group screenshots by browser:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
resolveScreenshotPath: ({ arg, browserName, ext, root, testFileName }) =>
|
||||||
|
`${root}/screenshots/${browserName}/${testFileName}/${arg}${ext}`
|
||||||
|
```
|
||||||
|
|
||||||
|
## browser.expect.toMatchScreenshot.resolveDiffPath
|
||||||
|
|
||||||
|
- **Type:** `(data: PathResolveData) => string`
|
||||||
|
- **Default output:** `` `${root}/${attachmentsDir}/${testFileDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}` ``
|
||||||
|
|
||||||
|
A function to customize where diff images are stored when screenshot comparisons
|
||||||
|
fail. Receives the same data object as
|
||||||
|
[`resolveScreenshotPath`](#browser-expect-tomatchscreenshot-resolvescreenshotpath).
|
||||||
|
|
||||||
|
For example, to store diffs in a subdirectory of attachments:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
resolveDiffPath: ({ arg, attachmentsDir, browserName, ext, root, testFileName }) =>
|
||||||
|
`${root}/${attachmentsDir}/screenshot-diffs/${testFileName}/${arg}-${browserName}${ext}`
|
||||||
|
```
|
||||||
|
|
||||||
|
## browser.expect.toMatchScreenshot.comparators
|
||||||
|
|
||||||
|
- **Type:** `Record<string, Comparator>`
|
||||||
|
|
||||||
|
Register custom screenshot comparison algorithms, like [SSIM](https://en.wikipedia.org/wiki/Structural_similarity_index_measure) or other perceptual similarity metrics.
|
||||||
|
|
||||||
|
To create a custom comparator, you need to register it in your config. If using TypeScript, declare its options in the `ScreenshotComparatorRegistry` interface.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
// 1. Declare the comparator's options type
|
||||||
|
declare module 'vitest/browser' {
|
||||||
|
interface ScreenshotComparatorRegistry {
|
||||||
|
myCustomComparator: {
|
||||||
|
sensitivity?: number
|
||||||
|
ignoreColors?: boolean
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 2. Implement the comparator
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
browser: {
|
||||||
|
expect: {
|
||||||
|
toMatchScreenshot: {
|
||||||
|
comparators: {
|
||||||
|
myCustomComparator: async (
|
||||||
|
reference,
|
||||||
|
actual,
|
||||||
|
{
|
||||||
|
createDiff, // always provided by Vitest
|
||||||
|
sensitivity = 0.01,
|
||||||
|
ignoreColors = false,
|
||||||
|
}
|
||||||
|
) => {
|
||||||
|
// ...algorithm implementation
|
||||||
|
return { pass, diff, message }
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Then use it in your tests:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
await expect(locator).toMatchScreenshot({
|
||||||
|
comparatorName: 'myCustomComparator',
|
||||||
|
comparatorOptions: {
|
||||||
|
sensitivity: 0.08,
|
||||||
|
ignoreColors: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
**Comparator Function Signature:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
type Comparator<Options> = (
|
||||||
|
reference: {
|
||||||
|
metadata: { height: number; width: number }
|
||||||
|
data: TypedArray
|
||||||
|
},
|
||||||
|
actual: {
|
||||||
|
metadata: { height: number; width: number }
|
||||||
|
data: TypedArray
|
||||||
|
},
|
||||||
|
options: {
|
||||||
|
createDiff: boolean
|
||||||
|
} & Options
|
||||||
|
) => Promise<{
|
||||||
|
pass: boolean
|
||||||
|
diff: TypedArray | null
|
||||||
|
message: string | null
|
||||||
|
}> | {
|
||||||
|
pass: boolean
|
||||||
|
diff: TypedArray | null
|
||||||
|
message: string | null
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `reference` and `actual` images are decoded using the appropriate codec (currently only PNG). The `data` property is a flat `TypedArray` (`Buffer`, `Uint8Array`, or `Uint8ClampedArray`) containing pixel data in RGBA format:
|
||||||
|
|
||||||
|
- **4 bytes per pixel**: red, green, blue, alpha (from `0` to `255` each)
|
||||||
|
- **Row-major order**: pixels are stored left-to-right, top-to-bottom
|
||||||
|
- **Total length**: `width × height × 4` bytes
|
||||||
|
- **Alpha channel**: always present. Images without transparency have alpha values set to `255` (fully opaque)
|
||||||
|
|
||||||
|
::: tip Performance Considerations
|
||||||
|
The `createDiff` option indicates whether a diff image is needed. During [stable screenshot detection](/guide/browser/visual-regression-testing#how-visual-tests-work), Vitest calls comparators with `createDiff: false` to avoid unnecessary work.
|
||||||
|
|
||||||
|
**Respect this flag to keep your tests fast**.
|
||||||
|
:::
|
||||||
|
|
||||||
|
::: warning Handle Missing Options
|
||||||
|
The `options` parameter in `toMatchScreenshot()` is optional, so users might not provide all your comparator options. Always make them optional with default values:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
myCustomComparator: (
|
||||||
|
reference,
|
||||||
|
actual,
|
||||||
|
{ createDiff, threshold = 0.1, maxDiff = 100 },
|
||||||
|
) => {
|
||||||
|
// ...comparison logic
|
||||||
|
}
|
||||||
|
```
|
||||||
|
:::
|
||||||
12
docs/config/browser/headless.md
Normal file
12
docs/config/browser/headless.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: browser.headless | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.headless
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `process.env.CI`
|
||||||
|
- **CLI:** `--browser.headless`, `--browser.headless=false`
|
||||||
|
|
||||||
|
Run the browser in a `headless` mode. If you are running Vitest in CI, it will be enabled by default.
|
||||||
52
docs/config/browser/instances.md
Normal file
52
docs/config/browser/instances.md
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
---
|
||||||
|
title: browser.instances | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.instances
|
||||||
|
|
||||||
|
- **Type:** `BrowserConfig`
|
||||||
|
- **Default:** `[]`
|
||||||
|
|
||||||
|
Defines multiple browser setups. Every config has to have at least a `browser` field.
|
||||||
|
|
||||||
|
You can specify most of the [project options](/config/) (not marked with a <CRoot /> icon) and some of the `browser` options like `browser.testerHtmlPath`.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
Every browser config inherits options from the root config:
|
||||||
|
|
||||||
|
```ts{3,9} [vitest.config.ts]
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
setupFile: ['./root-setup-file.js'],
|
||||||
|
browser: {
|
||||||
|
enabled: true,
|
||||||
|
testerHtmlPath: './custom-path.html',
|
||||||
|
instances: [
|
||||||
|
{
|
||||||
|
// will have both setup files: "root" and "browser"
|
||||||
|
setupFile: ['./browser-setup-file.js'],
|
||||||
|
// implicitly has "testerHtmlPath" from the root config // [!code warning]
|
||||||
|
// testerHtmlPath: './custom-path.html', // [!code warning]
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
For more examples, refer to the ["Multiple Setups" guide](/guide/browser/multiple-setups).
|
||||||
|
:::
|
||||||
|
|
||||||
|
List of available `browser` options:
|
||||||
|
|
||||||
|
- `browser` (the name of the browser)
|
||||||
|
- [`headless`](/config/browser/headless)
|
||||||
|
- [`locators`](/config/browser/locators)
|
||||||
|
- [`viewport`](/config/browser/viewport)
|
||||||
|
- [`testerHtmlPath`](/config/browser/testerhtmlpath)
|
||||||
|
- [`screenshotDirectory`](/config/browser/screenshotdirectory)
|
||||||
|
- [`screenshotFailures`](/config/browser/screenshotfailures)
|
||||||
|
- [`provider`](/config/browser/provider)
|
||||||
|
|
||||||
|
Under the hood, Vitest transforms these instances into separate [test projects](/api/advanced/test-project) sharing a single Vite server for better caching performance.
|
||||||
16
docs/config/browser/isolate.md
Normal file
16
docs/config/browser/isolate.md
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
title: browser.isolate | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.isolate <Deprecated />
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** the same as [`--isolate`](/config/#isolate)
|
||||||
|
- **CLI:** `--browser.isolate`, `--browser.isolate=false`
|
||||||
|
|
||||||
|
Run every test in a separate iframe.
|
||||||
|
|
||||||
|
::: danger DEPRECATED
|
||||||
|
This option is deprecated. Use [`isolate`](/config/#isolate) instead.
|
||||||
|
:::
|
||||||
15
docs/config/browser/locators.md
Normal file
15
docs/config/browser/locators.md
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
title: browser.locators | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.locators
|
||||||
|
|
||||||
|
Options for built-in [browser locators](/api/browser/locators).
|
||||||
|
|
||||||
|
## browser.locators.testIdAttribute
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **Default:** `data-testid`
|
||||||
|
|
||||||
|
Attribute used to find elements with `getByTestId` locator.
|
||||||
44
docs/config/browser/orchestratorscripts.md
Normal file
44
docs/config/browser/orchestratorscripts.md
Normal file
@ -0,0 +1,44 @@
|
|||||||
|
---
|
||||||
|
title: browser.orchestratorScripts | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.orchestratorScripts
|
||||||
|
|
||||||
|
- **Type:** `BrowserScript[]`
|
||||||
|
- **Default:** `[]`
|
||||||
|
|
||||||
|
Custom scripts that should be injected into the orchestrator HTML before test iframes are initiated. This HTML document only sets up iframes and doesn't actually import your code.
|
||||||
|
|
||||||
|
The script `src` and `content` will be processed by Vite plugins. Script should be provided in the following shape:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export interface BrowserScript {
|
||||||
|
/**
|
||||||
|
* If "content" is provided and type is "module", this will be its identifier.
|
||||||
|
*
|
||||||
|
* If you are using TypeScript, you can add `.ts` extension here for example.
|
||||||
|
* @default `injected-${index}.js`
|
||||||
|
*/
|
||||||
|
id?: string
|
||||||
|
/**
|
||||||
|
* JavaScript content to be injected. This string is processed by Vite plugins if type is "module".
|
||||||
|
*
|
||||||
|
* You can use `id` to give Vite a hint about the file extension.
|
||||||
|
*/
|
||||||
|
content?: string
|
||||||
|
/**
|
||||||
|
* Path to the script. This value is resolved by Vite so it can be a node module or a file path.
|
||||||
|
*/
|
||||||
|
src?: string
|
||||||
|
/**
|
||||||
|
* If the script should be loaded asynchronously.
|
||||||
|
*/
|
||||||
|
async?: boolean
|
||||||
|
/**
|
||||||
|
* Script type.
|
||||||
|
* @default 'module'
|
||||||
|
*/
|
||||||
|
type?: string
|
||||||
|
}
|
||||||
|
```
|
||||||
@ -62,7 +62,7 @@ Unlike Playwright test runner, Vitest opens a _single_ page to run all tests tha
|
|||||||
These options are directly passed down to `playwright[browser].launch` command. You can read more about the command and available arguments in the [Playwright documentation](https://playwright.dev/docs/api/class-browsertype#browser-type-launch).
|
These options are directly passed down to `playwright[browser].launch` command. You can read more about the command and available arguments in the [Playwright documentation](https://playwright.dev/docs/api/class-browsertype#browser-type-launch).
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
Vitest will ignore `launch.headless` option. Instead, use [`test.browser.headless`](/guide/browser/config#browser-headless).
|
Vitest will ignore `launch.headless` option. Instead, use [`test.browser.headless`](/config/browser/headless).
|
||||||
|
|
||||||
Note that Vitest will push debugging flags to `launch.args` if [`--inspect`](/guide/cli#inspect) is enabled.
|
Note that Vitest will push debugging flags to `launch.args` if [`--inspect`](/guide/cli#inspect) is enabled.
|
||||||
:::
|
:::
|
||||||
@ -86,14 +86,14 @@ Note that the context is created for every _test file_, not every _test_ like in
|
|||||||
::: warning
|
::: warning
|
||||||
Vitest always sets `ignoreHTTPSErrors` to `true` in case your server is served via HTTPS and `serviceWorkers` to `'allow'` to support module mocking via [MSW](https://mswjs.io).
|
Vitest always sets `ignoreHTTPSErrors` to `true` in case your server is served via HTTPS and `serviceWorkers` to `'allow'` to support module mocking via [MSW](https://mswjs.io).
|
||||||
|
|
||||||
It is also recommended to use [`test.browser.viewport`](/guide/browser/config#browser-headless) instead of specifying it here as it will be lost when tests are running in headless mode.
|
It is also recommended to use [`test.browser.viewport`](/config/browser/headless) instead of specifying it here as it will be lost when tests are running in headless mode.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
## `actionTimeout`
|
## `actionTimeout`
|
||||||
|
|
||||||
- **Default:** no timeout
|
- **Default:** no timeout
|
||||||
|
|
||||||
This value configures the default timeout it takes for Playwright to wait until all accessibility checks pass and [the action](/guide/browser/interactivity-api) is actually done.
|
This value configures the default timeout it takes for Playwright to wait until all accessibility checks pass and [the action](/api/browser/interactivity) is actually done.
|
||||||
|
|
||||||
You can also configure the action timeout per-action:
|
You can also configure the action timeout per-action:
|
||||||
|
|
||||||
@ -1,7 +1,7 @@
|
|||||||
# Configuring Preview
|
# Configuring Preview
|
||||||
|
|
||||||
::: warning
|
::: warning
|
||||||
The `preview` provider's main functionality is to show tests in a real browser environment. However, it does not support advanced browser automation features like multiple browser instances or headless mode. For more complex scenarios, consider using [Playwright](/guide/browser/playwright) or [WebdriverIO](/guide/browser/webdriverio).
|
The `preview` provider's main functionality is to show tests in a real browser environment. However, it does not support advanced browser automation features like multiple browser instances or headless mode. For more complex scenarios, consider using [Playwright](/config/browser/playwright) or [WebdriverIO](/config/browser/webdriverio).
|
||||||
:::
|
:::
|
||||||
|
|
||||||
To see your tests running in a real browser, you need to install the [`@vitest/browser-preview`](https://www.npmjs.com/package/@vitest/browser-preview) npm package and specify its `preview` export in the `test.browser.provider` property of your config:
|
To see your tests running in a real browser, you need to install the [`@vitest/browser-preview`](https://www.npmjs.com/package/@vitest/browser-preview) npm package and specify its `preview` export in the `test.browser.provider` property of your config:
|
||||||
@ -24,9 +24,9 @@ This will open a new browser window using your default browser to run the tests.
|
|||||||
|
|
||||||
## Differences with Other Providers
|
## Differences with Other Providers
|
||||||
|
|
||||||
The preview provider has some limitations compared to other providers like [Playwright](/guide/browser/playwright) or [WebdriverIO](/guide/browser/webdriverio):
|
The preview provider has some limitations compared to other providers like [Playwright](/config/browser/playwright) or [WebdriverIO](/config/browser/webdriverio):
|
||||||
|
|
||||||
- It does not support headless mode; the browser window will always be visible.
|
- It does not support headless mode; the browser window will always be visible.
|
||||||
- It does not support multiple instances of the same browser; each instance must use a different browser.
|
- It does not support multiple instances of the same browser; each instance must use a different browser.
|
||||||
- It does not support advanced browser capabilities or options; you can only specify the browser name.
|
- It does not support advanced browser capabilities or options; you can only specify the browser name.
|
||||||
- It does not support CDP (Chrome DevTools Protocol) commands or other low-level browser interactions. Unlike Playwright or WebdriverIO, the [`userEvent`](/guide/browser/interactivity-api) API is just re-exported from [`@testing-library/user-event`](https://www.npmjs.com/package/@testing-library/user-event) and does not have any special integration with the browser.
|
- It does not support CDP (Chrome DevTools Protocol) commands or other low-level browser interactions. Unlike Playwright or WebdriverIO, the [`userEvent`](/api/browser/interactivity) API is just re-exported from [`@testing-library/user-event`](https://www.npmjs.com/package/@testing-library/user-event) and does not have any special integration with the browser.
|
||||||
86
docs/config/browser/provider.md
Normal file
86
docs/config/browser/provider.md
Normal file
@ -0,0 +1,86 @@
|
|||||||
|
---
|
||||||
|
title: browser.provider | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.provider {#browser-provider}
|
||||||
|
|
||||||
|
- **Type:** `BrowserProviderOption`
|
||||||
|
- **Default:** `'preview'`
|
||||||
|
- **CLI:** `--browser.provider=playwright`
|
||||||
|
|
||||||
|
The return value of the provider factory. You can import the factory from `@vitest/browser-<provider-name>` or make your own provider:
|
||||||
|
|
||||||
|
```ts{8-10}
|
||||||
|
import { playwright } from '@vitest/browser-playwright'
|
||||||
|
import { webdriverio } from '@vitest/browser-webdriverio'
|
||||||
|
import { preview } from '@vitest/browser-preview'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
browser: {
|
||||||
|
provider: playwright(),
|
||||||
|
provider: webdriverio(),
|
||||||
|
provider: preview(),
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
To configure how provider initializes the browser, you can pass down options to the factory function:
|
||||||
|
|
||||||
|
```ts{7-13,20-26}
|
||||||
|
import { playwright } from '@vitest/browser-playwright'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
browser: {
|
||||||
|
// shared provider options between all instances
|
||||||
|
provider: playwright({
|
||||||
|
launchOptions: {
|
||||||
|
slowMo: 50,
|
||||||
|
channel: 'chrome-beta',
|
||||||
|
},
|
||||||
|
actionTimeout: 5_000,
|
||||||
|
}),
|
||||||
|
instances: [
|
||||||
|
{ browser: 'chromium' },
|
||||||
|
{
|
||||||
|
browser: 'firefox',
|
||||||
|
// overriding options only for a single instance
|
||||||
|
// this will NOT merge options with the parent one
|
||||||
|
provider: playwright({
|
||||||
|
launchOptions: {
|
||||||
|
firefoxUserPrefs: {
|
||||||
|
'browser.startup.homepage': 'https://example.com',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
## Custom Provider <Badge type="danger">advanced</Badge>
|
||||||
|
|
||||||
|
::: danger ADVANCED API
|
||||||
|
The custom provider API is highly experimental and can change between patches. If you just need to run tests in a browser, use the [`browser.instances`](#browser-instances) option instead.
|
||||||
|
:::
|
||||||
|
|
||||||
|
```ts
|
||||||
|
export interface BrowserProvider {
|
||||||
|
name: string
|
||||||
|
mocker?: BrowserModuleMocker
|
||||||
|
readonly initScripts?: string[]
|
||||||
|
/**
|
||||||
|
* @experimental opt-in into file parallelisation
|
||||||
|
*/
|
||||||
|
supportsParallelism: boolean
|
||||||
|
getCommandsContext: (sessionId: string) => Record<string, unknown>
|
||||||
|
openPage: (sessionId: string, url: string) => Promise<void>
|
||||||
|
getCDPSession?: (sessionId: string) => Promise<CDPSession>
|
||||||
|
close: () => Awaitable<void>
|
||||||
|
}
|
||||||
|
```
|
||||||
11
docs/config/browser/screenshotdirectory.md
Normal file
11
docs/config/browser/screenshotdirectory.md
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
title: browser.screenshotDirectory | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.screenshotDirectory
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **Default:** `__screenshots__` in the test file directory
|
||||||
|
|
||||||
|
Path to the screenshots directory relative to the `root`.
|
||||||
11
docs/config/browser/screenshotfailures.md
Normal file
11
docs/config/browser/screenshotfailures.md
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
title: browser.screenshotFailures | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.screenshotFailures
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `!browser.ui`
|
||||||
|
|
||||||
|
Should Vitest take screenshots if the test fails.
|
||||||
10
docs/config/browser/testerhtmlpath.md
Normal file
10
docs/config/browser/testerhtmlpath.md
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
---
|
||||||
|
title: browser.testerHtmlPath | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.testerHtmlPath
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
|
||||||
|
A path to the HTML entry point. Can be relative to the root of the project. This file will be processed with [`transformIndexHtml`](https://vite.dev/guide/api-plugin#transformindexhtml) hook.
|
||||||
48
docs/config/browser/trace.md
Normal file
48
docs/config/browser/trace.md
Normal file
@ -0,0 +1,48 @@
|
|||||||
|
---
|
||||||
|
title: browser.trace | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.trace
|
||||||
|
|
||||||
|
- **Type:** `'on' | 'off' | 'on-first-retry' | 'on-all-retries' | 'retain-on-failure' | object`
|
||||||
|
- **CLI:** `--browser.trace=on`, `--browser.trace=retain-on-failure`
|
||||||
|
- **Default:** `'off'`
|
||||||
|
|
||||||
|
Capture a trace of your browser test runs. You can preview traces with [Playwright Trace Viewer](https://trace.playwright.dev/).
|
||||||
|
|
||||||
|
This options supports the following values:
|
||||||
|
|
||||||
|
- `'on'` - capture trace for all tests. (not recommended as it's performance heavy)
|
||||||
|
- `'off'` - do not capture traces.
|
||||||
|
- `'on-first-retry'` - capture trace only when retrying the test for the first time.
|
||||||
|
- `'on-all-retries'` - capture trace on every retry of the test.
|
||||||
|
- `'retain-on-failure'` - capture trace only for tests that fail. This will automatically delete traces for tests that pass.
|
||||||
|
- `object` - an object with the following shape:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface TraceOptions {
|
||||||
|
mode: 'on' | 'off' | 'on-first-retry' | 'on-all-retries' | 'retain-on-failure'
|
||||||
|
/**
|
||||||
|
* The directory where all traces will be stored. By default, Vitest
|
||||||
|
* stores all traces in `__traces__` folder close to the test file.
|
||||||
|
*/
|
||||||
|
tracesDir?: string
|
||||||
|
/**
|
||||||
|
* Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.
|
||||||
|
* @default true
|
||||||
|
*/
|
||||||
|
screenshots?: boolean
|
||||||
|
/**
|
||||||
|
* If this option is true tracing will
|
||||||
|
* - capture DOM snapshot on every action
|
||||||
|
* - record network activity
|
||||||
|
* @default true
|
||||||
|
*/
|
||||||
|
snapshots?: boolean
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
::: danger WARNING
|
||||||
|
This option is supported only by the [**playwright**](/config/browser/playwright) provider.
|
||||||
|
:::
|
||||||
15
docs/config/browser/trackunhandlederrors.md
Normal file
15
docs/config/browser/trackunhandlederrors.md
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
title: browser.trackUnhandledErrors | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.trackUnhandledErrors
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
|
||||||
|
Enables tracking uncaught errors and exceptions so they can be reported by Vitest.
|
||||||
|
|
||||||
|
If you need to hide certain errors, it is recommended to use [`onUnhandledError`](/config/#onunhandlederror) option instead.
|
||||||
|
|
||||||
|
Disabling this will completely remove all Vitest error handlers, which can help debugging with the "Pause on exceptions" checkbox turned on.
|
||||||
12
docs/config/browser/ui.md
Normal file
12
docs/config/browser/ui.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: browser.ui | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.ui
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `!isCI`
|
||||||
|
- **CLI:** `--browser.ui=false`
|
||||||
|
|
||||||
|
Should Vitest UI be injected into the page. By default, injects UI iframe during development.
|
||||||
11
docs/config/browser/viewport.md
Normal file
11
docs/config/browser/viewport.md
Normal file
@ -0,0 +1,11 @@
|
|||||||
|
---
|
||||||
|
title: browser.viewport | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# browser.viewport
|
||||||
|
|
||||||
|
- **Type:** `{ width, height }`
|
||||||
|
- **Default:** `414x896`
|
||||||
|
|
||||||
|
Default iframe's viewport.
|
||||||
@ -1,7 +1,7 @@
|
|||||||
# Configuring WebdriverIO
|
# Configuring WebdriverIO
|
||||||
|
|
||||||
::: info Playwright vs WebdriverIO
|
::: info Playwright vs WebdriverIO
|
||||||
If you do not already use WebdriverIO in your project, we recommend starting with [Playwright](/guide/browser/playwright) as it is easier to configure and has more flexible API.
|
If you do not already use WebdriverIO in your project, we recommend starting with [Playwright](/config/browser/playwright) as it is easier to configure and has more flexible API.
|
||||||
:::
|
:::
|
||||||
|
|
||||||
To run tests using WebdriverIO, you need to install the [`@vitest/browser-webdriverio`](https://www.npmjs.com/package/@vitest/browser-webdriverio) npm package and specify its `webdriverio` export in the `test.browser.provider` property of your config:
|
To run tests using WebdriverIO, you need to install the [`@vitest/browser-webdriverio`](https://www.npmjs.com/package/@vitest/browser-webdriverio) npm package and specify its `webdriverio` export in the `test.browser.provider` property of your config:
|
||||||
@ -60,5 +60,5 @@ You can find most available options in the [WebdriverIO documentation](https://w
|
|||||||
::: tip
|
::: tip
|
||||||
Most useful options are located on `capabilities` object. WebdriverIO allows nested capabilities, but Vitest will ignore those options because we rely on a different mechanism to spawn several browsers.
|
Most useful options are located on `capabilities` object. WebdriverIO allows nested capabilities, but Vitest will ignore those options because we rely on a different mechanism to spawn several browsers.
|
||||||
|
|
||||||
Note that Vitest will ignore `capabilities.browserName` — use [`test.browser.instances.browser`](/guide/browser/config#browser-capabilities-name) instead.
|
Note that Vitest will ignore `capabilities.browserName` — use [`test.browser.instances.browser`](/config/browser/instances#browser) instead.
|
||||||
:::
|
:::
|
||||||
31
docs/config/cache.md
Normal file
31
docs/config/cache.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
---
|
||||||
|
title: cache | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# cache <CRoot />
|
||||||
|
|
||||||
|
- **Type**: `false`
|
||||||
|
- **CLI**: `--no-cache`, `--cache=false`
|
||||||
|
|
||||||
|
Use this option if you want to disable the cache feature. At the moment Vitest stores cache for test results to run the longer and failed tests first.
|
||||||
|
|
||||||
|
The cache directory is controlled by the Vite's [`cacheDir`](https://vitejs.dev/config/shared-options.html#cachedir) option:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
cacheDir: 'custom-folder/.vitest'
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
You can limit the directory only for Vitest by using `process.env.VITEST`:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
cacheDir: process.env.VITEST ? 'custom-folder/.vitest' : undefined
|
||||||
|
})
|
||||||
|
```
|
||||||
34
docs/config/chaiconfig.md
Normal file
34
docs/config/chaiconfig.md
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
title: chaiConfig | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# chaiConfig
|
||||||
|
|
||||||
|
- **Type:** `{ includeStack?, showDiff?, truncateThreshold? }`
|
||||||
|
- **Default:** `{ includeStack: false, showDiff: true, truncateThreshold: 40 }`
|
||||||
|
|
||||||
|
Equivalent to [Chai config](https://github.com/chaijs/chai/blob/4.x.x/lib/chai/config.js).
|
||||||
|
|
||||||
|
## chaiConfig.includeStack
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Influences whether stack trace is included in Assertion error message. Default of false suppresses stack trace in the error message.
|
||||||
|
|
||||||
|
## chaiConfig.showDiff
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
|
||||||
|
Influences whether or not the `showDiff` flag should be included in the thrown AssertionErrors. `false` will always be `false`; `true` will be true when the assertion has requested a diff to be shown.
|
||||||
|
|
||||||
|
## chaiConfig.truncateThreshold
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `40`
|
||||||
|
|
||||||
|
Sets length threshold for actual and expected values in assertion errors. If this threshold is exceeded, for example for large data structures, the value is replaced with something like `[ Array(3) ]` or `{ Object (prop1, prop2) }`. Set it to `0` if you want to disable truncating altogether.
|
||||||
|
|
||||||
|
This config option affects truncating values in `test.each` titles and inside the assertion error message.
|
||||||
23
docs/config/clearmocks.md
Normal file
23
docs/config/clearmocks.md
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
---
|
||||||
|
title: clearMocks | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# clearMocks
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Should Vitest automatically call [`vi.clearAllMocks()`](/api/vi#vi-clearallmocks) before each test.
|
||||||
|
|
||||||
|
This will clear mock history without affecting mock implementations.
|
||||||
|
|
||||||
|
```js [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
clearMocks: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
397
docs/config/coverage.md
Normal file
397
docs/config/coverage.md
Normal file
@ -0,0 +1,397 @@
|
|||||||
|
---
|
||||||
|
title: coverage | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# coverage <CRoot /> {#coverage}
|
||||||
|
|
||||||
|
You can use [`v8`](/guide/coverage.html#v8-provider), [`istanbul`](/guide/coverage.html#istanbul-provider) or [a custom coverage solution](/guide/coverage#custom-coverage-provider) for coverage collection.
|
||||||
|
|
||||||
|
You can provide coverage options to CLI with dot notation:
|
||||||
|
|
||||||
|
```sh
|
||||||
|
npx vitest --coverage.enabled --coverage.provider=istanbul
|
||||||
|
```
|
||||||
|
|
||||||
|
::: 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.
|
||||||
|
:::
|
||||||
|
|
||||||
|
## coverage.provider
|
||||||
|
|
||||||
|
- **Type:** `'v8' | 'istanbul' | 'custom'`
|
||||||
|
- **Default:** `'v8'`
|
||||||
|
- **CLI:** `--coverage.provider=<provider>`
|
||||||
|
|
||||||
|
Use `provider` to select the tool for coverage collection.
|
||||||
|
|
||||||
|
## coverage.enabled
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.enabled`, `--coverage.enabled=false`
|
||||||
|
|
||||||
|
Enables coverage collection. Can be overridden using `--coverage` CLI option.
|
||||||
|
|
||||||
|
## coverage.include
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** Files that were imported during test run
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.include=<pattern>`, `--coverage.include=<pattern1> --coverage.include=<pattern2>`
|
||||||
|
|
||||||
|
List of files included in coverage as glob patterns. By default only files covered by tests are included.
|
||||||
|
|
||||||
|
It is recommended to pass file extensions in the pattern.
|
||||||
|
|
||||||
|
See [Including and excluding files from coverage report](/guide/coverage.html#including-and-excluding-files-from-coverage-report) for examples.
|
||||||
|
|
||||||
|
## coverage.exclude
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** : `[]`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.exclude=<path>`, `--coverage.exclude=<path1> --coverage.exclude=<path2>`
|
||||||
|
|
||||||
|
List of files excluded from coverage as glob patterns.
|
||||||
|
|
||||||
|
See [Including and excluding files from coverage report](/guide/coverage.html#including-and-excluding-files-from-coverage-report) for examples.
|
||||||
|
|
||||||
|
## coverage.clean
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.clean`, `--coverage.clean=false`
|
||||||
|
|
||||||
|
Clean coverage results before running tests
|
||||||
|
|
||||||
|
## coverage.cleanOnRerun
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.cleanOnRerun`, `--coverage.cleanOnRerun=false`
|
||||||
|
|
||||||
|
Clean coverage report on watch rerun. Set to `false` to preserve coverage results from previous run in watch mode.
|
||||||
|
|
||||||
|
## coverage.reportsDirectory
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **Default:** `'./coverage'`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.reportsDirectory=<path>`
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
Vitest will delete this directory before running tests if `coverage.clean` is enabled (default value).
|
||||||
|
:::
|
||||||
|
|
||||||
|
Directory to write coverage report to.
|
||||||
|
|
||||||
|
To preview the coverage report in the output of [HTML reporter](/guide/reporters.html#html-reporter), this option must be set as a sub-directory of the html report directory (for example `./html/coverage`).
|
||||||
|
|
||||||
|
## coverage.reporter
|
||||||
|
|
||||||
|
- **Type:** `string | string[] | [string, {}][]`
|
||||||
|
- **Default:** `['text', 'html', 'clover', 'json']`
|
||||||
|
- **Available for providers:** `'v8' | '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. See [`@types/istanbul-reporter`](https://github.com/DefinitelyTyped/DefinitelyTyped/blob/276d95e4304b3670eaf6e8e5a7ea9e265a14e338/types/istanbul-reports/index.d.ts) for details about reporter specific options.
|
||||||
|
|
||||||
|
The reporter has three different types:
|
||||||
|
|
||||||
|
- A single reporter: `{ reporter: 'html' }`
|
||||||
|
- Multiple reporters without options: `{ reporter: ['html', 'json'] }`
|
||||||
|
- A single or multiple reporters with reporter options:
|
||||||
|
<!-- eslint-skip -->
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
reporter: [
|
||||||
|
['lcov', { 'projectRoot': './src' }],
|
||||||
|
['json', { 'file': 'coverage.json' }],
|
||||||
|
['text']
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also pass custom coverage reporters. See [Guide - Custom Coverage Reporter](/guide/coverage#custom-coverage-reporter) for more information.
|
||||||
|
|
||||||
|
<!-- eslint-skip -->
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
reporter: [
|
||||||
|
// Specify reporter using name of the NPM package
|
||||||
|
'@vitest/custom-coverage-reporter',
|
||||||
|
['@vitest/custom-coverage-reporter', { someOption: true }],
|
||||||
|
|
||||||
|
// Specify reporter using local path
|
||||||
|
'/absolute/path/to/custom-reporter.cjs',
|
||||||
|
['/absolute/path/to/custom-reporter.cjs', { someOption: true }],
|
||||||
|
]
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
You can check your coverage report in Vitest UI: check [Vitest UI Coverage](/guide/coverage#vitest-ui) for more details.
|
||||||
|
|
||||||
|
## coverage.reportOnFailure {#coverage-reportonfailure}
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.reportOnFailure`, `--coverage.reportOnFailure=false`
|
||||||
|
|
||||||
|
Generate coverage report even when tests fail.
|
||||||
|
|
||||||
|
## coverage.allowExternal
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.allowExternal`, `--coverage.allowExternal=false`
|
||||||
|
|
||||||
|
Collect coverage of files outside the [project `root`](#root).
|
||||||
|
|
||||||
|
## coverage.excludeAfterRemap
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.excludeAfterRemap`, `--coverage.excludeAfterRemap=false`
|
||||||
|
|
||||||
|
Apply exclusions again after coverage has been remapped to original sources.
|
||||||
|
This is useful when your source files are transpiled and may contain source maps of non-source files.
|
||||||
|
|
||||||
|
Use this option when you are seeing files that show up in report even if they match your `coverage.exclude` patterns.
|
||||||
|
|
||||||
|
## coverage.skipFull
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.skipFull`, `--coverage.skipFull=false`
|
||||||
|
|
||||||
|
Do not show files with 100% statement, branch, and function coverage.
|
||||||
|
|
||||||
|
## coverage.thresholds
|
||||||
|
|
||||||
|
Options for coverage thresholds.
|
||||||
|
|
||||||
|
If a threshold is set to a positive number, it will be interpreted as the minimum percentage of coverage required. For example, setting the lines threshold to `90` means that 90% of lines must be covered.
|
||||||
|
|
||||||
|
If a threshold is set to a negative number, it will be treated as the maximum number of uncovered items allowed. For example, setting the lines threshold to `-10` means that no more than 10 lines may be uncovered.
|
||||||
|
|
||||||
|
<!-- eslint-skip -->
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
coverage: {
|
||||||
|
thresholds: {
|
||||||
|
// Requires 90% function coverage
|
||||||
|
functions: 90,
|
||||||
|
|
||||||
|
// Require that no more than 10 lines are uncovered
|
||||||
|
lines: -10,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### coverage.thresholds.lines
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.thresholds.lines=<number>`
|
||||||
|
|
||||||
|
Global threshold for lines.
|
||||||
|
|
||||||
|
### coverage.thresholds.functions
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.thresholds.functions=<number>`
|
||||||
|
|
||||||
|
Global threshold for functions.
|
||||||
|
|
||||||
|
### coverage.thresholds.branches
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.thresholds.branches=<number>`
|
||||||
|
|
||||||
|
Global threshold for branches.
|
||||||
|
|
||||||
|
### coverage.thresholds.statements
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.thresholds.statements=<number>`
|
||||||
|
|
||||||
|
Global threshold for statements.
|
||||||
|
|
||||||
|
### coverage.thresholds.perFile
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.thresholds.perFile`, `--coverage.thresholds.perFile=false`
|
||||||
|
|
||||||
|
Check thresholds per file.
|
||||||
|
|
||||||
|
### coverage.thresholds.autoUpdate
|
||||||
|
|
||||||
|
- **Type:** `boolean | function`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.thresholds.autoUpdate=<boolean>`
|
||||||
|
|
||||||
|
Update all threshold values `lines`, `functions`, `branches` and `statements` to configuration file when current coverage is better than the configured thresholds.
|
||||||
|
This option helps to maintain thresholds when coverage is improved.
|
||||||
|
|
||||||
|
You can also pass a function for formatting the updated threshold values:
|
||||||
|
|
||||||
|
<!-- eslint-skip -->
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
coverage: {
|
||||||
|
thresholds: {
|
||||||
|
// Update thresholds without decimals
|
||||||
|
autoUpdate: (newThreshold) => Math.floor(newThreshold),
|
||||||
|
|
||||||
|
// 95.85 -> 95
|
||||||
|
functions: 95,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### coverage.thresholds.100
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.thresholds.100`, `--coverage.thresholds.100=false`
|
||||||
|
|
||||||
|
Sets global thresholds to 100.
|
||||||
|
Shortcut for `--coverage.thresholds.lines 100 --coverage.thresholds.functions 100 --coverage.thresholds.branches 100 --coverage.thresholds.statements 100`.
|
||||||
|
|
||||||
|
### coverage.thresholds[glob-pattern]
|
||||||
|
|
||||||
|
- **Type:** `{ statements?: number functions?: number branches?: number lines?: number }`
|
||||||
|
- **Default:** `undefined`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
|
||||||
|
Sets thresholds for files matching the glob pattern.
|
||||||
|
|
||||||
|
::: tip NOTE
|
||||||
|
Vitest counts all files, including those covered by glob-patterns, into the global coverage thresholds.
|
||||||
|
This is different from Jest behavior.
|
||||||
|
:::
|
||||||
|
|
||||||
|
<!-- eslint-skip -->
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
coverage: {
|
||||||
|
thresholds: {
|
||||||
|
// Thresholds for all files
|
||||||
|
functions: 95,
|
||||||
|
branches: 70,
|
||||||
|
|
||||||
|
// Thresholds for matching glob pattern
|
||||||
|
'src/utils/**.ts': {
|
||||||
|
statements: 95,
|
||||||
|
functions: 90,
|
||||||
|
branches: 85,
|
||||||
|
lines: 80,
|
||||||
|
},
|
||||||
|
|
||||||
|
// Files matching this pattern will only have lines thresholds set.
|
||||||
|
// Global thresholds are not inherited.
|
||||||
|
'**/math.ts': {
|
||||||
|
lines: 100,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
### coverage.thresholds[glob-pattern].100
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
|
||||||
|
Sets thresholds to 100 for files matching the glob pattern.
|
||||||
|
|
||||||
|
<!-- eslint-skip -->
|
||||||
|
```ts
|
||||||
|
{
|
||||||
|
coverage: {
|
||||||
|
thresholds: {
|
||||||
|
// Thresholds for all files
|
||||||
|
functions: 95,
|
||||||
|
branches: 70,
|
||||||
|
|
||||||
|
// Thresholds for matching glob pattern
|
||||||
|
'src/utils/**.ts': { 100: true },
|
||||||
|
'**/math.ts': { 100: true }
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## coverage.ignoreClassMethods
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** `[]`
|
||||||
|
- **Available for providers:** `'v8' | '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.
|
||||||
|
|
||||||
|
## coverage.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:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.watermarks.statements=50,80`, `--coverage.watermarks.branches=50,80`
|
||||||
|
|
||||||
|
Watermarks for statements, lines, branches and functions. See [istanbul documentation](https://github.com/istanbuljs/nyc#high-and-low-watermarks) for more information.
|
||||||
|
|
||||||
|
## coverage.processingConcurrency
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `Math.min(20, os.availableParallelism?.() ?? os.cpus().length)`
|
||||||
|
- **Available for providers:** `'v8' | 'istanbul'`
|
||||||
|
- **CLI:** `--coverage.processingConcurrency=<number>`
|
||||||
|
|
||||||
|
Concurrency limit used when processing the coverage results.
|
||||||
|
|
||||||
|
## coverage.customProviderModule
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **Available for providers:** `'custom'`
|
||||||
|
- **CLI:** `--coverage.customProviderModule=<path or module name>`
|
||||||
|
|
||||||
|
Specifies the module name or path for the custom coverage provider module. See [Guide - Custom Coverage Provider](/guide/coverage#custom-coverage-provider) for more information.
|
||||||
52
docs/config/css.md
Normal file
52
docs/config/css.md
Normal file
@ -0,0 +1,52 @@
|
|||||||
|
---
|
||||||
|
title: css | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
This option is not applied to [browser tests](/guide/browser/).
|
||||||
|
:::
|
||||||
|
|
||||||
|
## 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 `/.+/`.
|
||||||
|
:::
|
||||||
|
|
||||||
|
## css.exclude
|
||||||
|
|
||||||
|
- **Type**: `RegExp | RegExp[]`
|
||||||
|
- **Default**: `[]`
|
||||||
|
|
||||||
|
RegExp pattern for files that will return an empty CSS file.
|
||||||
|
|
||||||
|
## css.modules
|
||||||
|
|
||||||
|
- **Type**: `{ classNameStrategy? }`
|
||||||
|
- **Default**: `{}`
|
||||||
|
|
||||||
|
### css.modules.classNameStrategy
|
||||||
|
|
||||||
|
- **Type**: `'stable' | 'scoped' | 'non-scoped'`
|
||||||
|
- **Default**: `'stable'`
|
||||||
|
|
||||||
|
If you decide to process CSS files, you can configure if class names inside CSS modules should be scoped. You can choose one of the options:
|
||||||
|
|
||||||
|
- `stable`: class names will be generated as `_${name}_${hashedFilename}`, which means that generated class will stay the same, if CSS content is changed, but will change, if the name of the file is modified, or file is moved to another folder. This setting is useful, if you use snapshot feature.
|
||||||
|
- `scoped`: class names will be generated as usual, respecting `css.modules.generateScopedName` method, if you have one and CSS processing is enabled. By default, filename will be generated as `_${name}_${hash}`, where hash includes filename and content of the file.
|
||||||
|
- `non-scoped`: class names will not be hashed.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
By default, Vitest exports a proxy, bypassing CSS Modules processing. If you rely on CSS properties on your classes, you have to enable CSS processing using `include` option.
|
||||||
|
:::
|
||||||
28
docs/config/dangerouslyignoreunhandlederrors.md
Normal file
28
docs/config/dangerouslyignoreunhandlederrors.md
Normal file
@ -0,0 +1,28 @@
|
|||||||
|
---
|
||||||
|
title: dangerouslyIgnoreUnhandledErrors | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# dangerouslyIgnoreUnhandledErrors <CRoot />
|
||||||
|
|
||||||
|
- **Type**: `boolean`
|
||||||
|
- **Default**: `false`
|
||||||
|
- **CLI:**
|
||||||
|
- `--dangerouslyIgnoreUnhandledErrors`
|
||||||
|
- `--dangerouslyIgnoreUnhandledErrors=false`
|
||||||
|
|
||||||
|
If this option is set to `true`, Vitest will not fail the test run if there are unhandled errors. Note that built-in reporters will still report them.
|
||||||
|
|
||||||
|
If you want to filter out certain errors conditionally, use [`onUnhandledError`](/config/onunhandlederror) callback instead.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```js [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
dangerouslyIgnoreUnhandledErrors: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
132
docs/config/deps.md
Normal file
132
docs/config/deps.md
Normal file
@ -0,0 +1,132 @@
|
|||||||
|
---
|
||||||
|
title: deps | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# deps
|
||||||
|
|
||||||
|
- **Type:** `{ optimizer?, ... }`
|
||||||
|
|
||||||
|
Handling for dependencies resolution.
|
||||||
|
|
||||||
|
## deps.optimizer {#deps-optimizer}
|
||||||
|
|
||||||
|
- **Type:** `{ ssr?, client? }`
|
||||||
|
- **See also:** [Dep Optimization Options](https://vitejs.dev/config/dep-optimization-options.html)
|
||||||
|
|
||||||
|
Enable dependency optimization. If you have a lot of tests, this might improve their performance.
|
||||||
|
|
||||||
|
When Vitest encounters the external library listed in `include`, it will be bundled into a single file using esbuild and imported as a whole module. This is good for several reasons:
|
||||||
|
|
||||||
|
- Importing packages with a lot of imports is expensive. By bundling them into one file we can save a lot of time
|
||||||
|
- Importing UI libraries is expensive because they are not meant to run inside Node.js
|
||||||
|
- Your `alias` configuration is now respected inside bundled packages
|
||||||
|
- Code in your tests is running closer to how it's running in the browser
|
||||||
|
|
||||||
|
Be aware that only packages in `deps.optimizer?.[mode].include` option are bundled (some plugins populate this automatically, like Svelte). You can read more about available options in [Vite](https://vitejs.dev/config/dep-optimization-options.html) docs (Vitest doesn't support `disable` and `noDiscovery` options). By default, Vitest uses `optimizer.client` for `jsdom` and `happy-dom` environments, and `optimizer.ssr` for `node` and `edge` environments.
|
||||||
|
|
||||||
|
This options also inherits your `optimizeDeps` configuration (for web Vitest will extend `optimizeDeps`, for ssr - `ssr.optimizeDeps`). If you redefine `include`/`exclude` option in `deps.optimizer` it will extend your `optimizeDeps` when running tests. Vitest automatically removes the same options from `include`, if they are listed in `exclude`.
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
You will not be able to edit your `node_modules` code for debugging, since the code is actually located in your `cacheDir` or `test.cache.dir` directory. If you want to debug with `console.log` statements, edit it directly or force rebundling with `deps.optimizer?.[mode].force` option.
|
||||||
|
:::
|
||||||
|
|
||||||
|
### deps.optimizer.{mode}.enabled
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Enable dependency optimization.
|
||||||
|
|
||||||
|
## deps.client {#deps-client}
|
||||||
|
|
||||||
|
- **Type:** `{ transformAssets?, ... }`
|
||||||
|
|
||||||
|
Options that are applied to external files when the environment is set to `client`. By default, `jsdom` and `happy-dom` use `client` environment, while `node` and `edge` environments use `ssr`, so these options will have no affect on files inside those environments.
|
||||||
|
|
||||||
|
Usually, files inside `node_modules` are externalized, but these options also affect files in [`server.deps.external`](#server-deps-external).
|
||||||
|
|
||||||
|
### deps.client.transformAssets
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
|
||||||
|
Should Vitest process assets (.png, .svg, .jpg, etc) files and resolve them like Vite does in the browser.
|
||||||
|
|
||||||
|
This module will have a default export equal to the path to the asset, if no query is specified.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
At the moment, this option only works with [`vmThreads`](#vmthreads) and [`vmForks`](#vmforks) pools.
|
||||||
|
:::
|
||||||
|
|
||||||
|
### deps.client.transformCss
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
|
||||||
|
Should Vitest process CSS (.css, .scss, .sass, etc) files and resolve them like Vite does in the browser.
|
||||||
|
|
||||||
|
If CSS files are disabled with [`css`](#css) options, this option will just silence `ERR_UNKNOWN_FILE_EXTENSION` errors.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
At the moment, this option only works with [`vmThreads`](#vmthreads) and [`vmForks`](#vmforks) pools.
|
||||||
|
:::
|
||||||
|
|
||||||
|
### deps.client.transformGlobPattern
|
||||||
|
|
||||||
|
- **Type:** `RegExp | RegExp[]`
|
||||||
|
- **Default:** `[]`
|
||||||
|
|
||||||
|
Regexp pattern to match external files that should be transformed.
|
||||||
|
|
||||||
|
By default, files inside `node_modules` are externalized and not transformed, unless it's CSS or an asset, and corresponding option is not disabled.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
At the moment, this option only works with [`vmThreads`](#vmthreads) and [`vmForks`](#vmforks) pools.
|
||||||
|
:::
|
||||||
|
|
||||||
|
## deps.interopDefault
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
|
||||||
|
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, if this feature is disabled:
|
||||||
|
|
||||||
|
```
|
||||||
|
TypeError: createAsyncThunk is not a function
|
||||||
|
TypeError: default is not a function
|
||||||
|
```
|
||||||
|
|
||||||
|
By default, Vitest assumes you are using a bundler to bypass this and will not fail, but you can disable this behaviour manually, if your code is not processed.
|
||||||
|
|
||||||
|
## deps.moduleDirectories
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default**: `['node_modules']`
|
||||||
|
|
||||||
|
A list of directories that should be treated as module directories. This config option affects the behavior of [`vi.mock`](/api/vi#vi-mock): when no factory is provided and the path of what you are mocking matches one of the `moduleDirectories` values, Vitest will try to resolve the mock by looking for a `__mocks__` folder in the [root](#root) of the project.
|
||||||
|
|
||||||
|
This option will also affect if a file should be treated as a module when externalizing dependencies. By default, Vitest imports external modules with native Node.js bypassing Vite transformation step.
|
||||||
|
|
||||||
|
Setting this option will _override_ the default, if you wish to still search `node_modules` for packages include it along with any other options:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
deps: {
|
||||||
|
moduleDirectories: ['node_modules', path.resolve('../../packages')],
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
99
docs/config/diff.md
Normal file
99
docs/config/diff.md
Normal file
@ -0,0 +1,99 @@
|
|||||||
|
---
|
||||||
|
title: diff | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# diff
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **CLI:** `--diff=<path>`
|
||||||
|
|
||||||
|
`DiffOptions` object or a path to a module which exports `DiffOptions`. Useful if you want to customize diff display.
|
||||||
|
|
||||||
|
For example, as a config object:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
import c from 'picocolors'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
diff: {
|
||||||
|
aIndicator: c.bold('--'),
|
||||||
|
bIndicator: c.bold('++'),
|
||||||
|
omitAnnotationLines: true,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Or as a module:
|
||||||
|
|
||||||
|
:::code-group
|
||||||
|
```ts [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
diff: './vitest.diff.ts',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts [vitest.diff.ts]
|
||||||
|
import type { DiffOptions } from 'vitest'
|
||||||
|
import c from 'picocolors'
|
||||||
|
|
||||||
|
export default {
|
||||||
|
aIndicator: c.bold('--'),
|
||||||
|
bIndicator: c.bold('++'),
|
||||||
|
omitAnnotationLines: true,
|
||||||
|
} satisfies DiffOptions
|
||||||
|
```
|
||||||
|
:::
|
||||||
|
|
||||||
|
## diff.expand
|
||||||
|
|
||||||
|
- **Type**: `boolean`
|
||||||
|
- **Default**: `true`
|
||||||
|
- **CLI:** `--diff.expand=false`
|
||||||
|
|
||||||
|
Expand all common lines.
|
||||||
|
|
||||||
|
## diff.truncateThreshold
|
||||||
|
|
||||||
|
- **Type**: `number`
|
||||||
|
- **Default**: `0`
|
||||||
|
- **CLI:** `--diff.truncateThreshold=<path>`
|
||||||
|
|
||||||
|
The maximum length of diff result to be displayed. Diffs above this threshold will be truncated.
|
||||||
|
Truncation won't take effect with default value 0.
|
||||||
|
|
||||||
|
## diff.truncateAnnotation
|
||||||
|
|
||||||
|
- **Type**: `string`
|
||||||
|
- **Default**: `'... Diff result is truncated'`
|
||||||
|
- **CLI:** `--diff.truncateAnnotation=<annotation>`
|
||||||
|
|
||||||
|
Annotation that is output at the end of diff result if it's truncated.
|
||||||
|
|
||||||
|
## diff.truncateAnnotationColor
|
||||||
|
|
||||||
|
- **Type**: `DiffOptionsColor = (arg: string) => string`
|
||||||
|
- **Default**: `noColor = (string: string): string => string`
|
||||||
|
|
||||||
|
Color of truncate annotation, default is output with no color.
|
||||||
|
|
||||||
|
## diff.printBasicPrototype
|
||||||
|
|
||||||
|
- **Type**: `boolean`
|
||||||
|
- **Default**: `false`
|
||||||
|
|
||||||
|
Print basic prototype `Object` and `Array` in diff output
|
||||||
|
|
||||||
|
## diff.maxDepth
|
||||||
|
|
||||||
|
- **Type**: `number`
|
||||||
|
- **Default**: `20` (or `8` when comparing different types)
|
||||||
|
|
||||||
|
Limit the depth to recurse when printing nested objects
|
||||||
12
docs/config/dir.md
Normal file
12
docs/config/dir.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: dir | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# dir
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **CLI:** `--dir=<path>`
|
||||||
|
- **Default:** same as `root`
|
||||||
|
|
||||||
|
Base directory to scan for the test files. You can specify this option to speed up test discovery if your root covers the whole project
|
||||||
20
docs/config/disableconsoleintercept.md
Normal file
20
docs/config/disableconsoleintercept.md
Normal file
@ -0,0 +1,20 @@
|
|||||||
|
---
|
||||||
|
title: disableConsoleIntercept | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# disableConsoleIntercept
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **CLI:** `--disableConsoleIntercept`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
By default, Vitest automatically intercepts console logging during tests for extra formatting of test file, test title, etc.
|
||||||
|
|
||||||
|
This is also required for console log preview on Vitest UI.
|
||||||
|
|
||||||
|
However, disabling such interception might help when you want to debug a code with normal synchronous terminal console logging.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
This option has no effect on [browser tests](/guide/browser/) since Vitest preserves original logging in browser devtools.
|
||||||
|
:::
|
||||||
10
docs/config/env.md
Normal file
10
docs/config/env.md
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
---
|
||||||
|
title: env | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# env
|
||||||
|
|
||||||
|
- **Type:** `Partial<NodeJS.ProcessEnv>`
|
||||||
|
|
||||||
|
Environment variables available on `process.env` and `import.meta.env` during tests. These variables will not be available in the main process (in `globalSetup`, for example).
|
||||||
100
docs/config/environment.md
Normal file
100
docs/config/environment.md
Normal file
@ -0,0 +1,100 @@
|
|||||||
|
---
|
||||||
|
title: environment | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
You can also use [Browser Mode](/guide/browser/) to run integration or unit tests in the browser without mocking the environment.
|
||||||
|
:::
|
||||||
|
|
||||||
|
To define custom options for your environment, use [`environmentOptions`](/config/environmentoptions).
|
||||||
|
|
||||||
|
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()
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
You can also define a custom environment. When non-builtin environment is used, Vitest will try to load the file if it's relative or absolute, or a package `vitest-environment-${name}`, if the name is a bare specifier.
|
||||||
|
|
||||||
|
The custom environment file should export an object with the shape of `Environment`:
|
||||||
|
|
||||||
|
```ts [environment.js]
|
||||||
|
import type { Environment } from 'vitest'
|
||||||
|
|
||||||
|
export default <Environment>{
|
||||||
|
name: 'custom',
|
||||||
|
viteEnvironment: 'ssr',
|
||||||
|
setup() {
|
||||||
|
// custom setup
|
||||||
|
return {
|
||||||
|
teardown() {
|
||||||
|
// called after all tests with this env have been run
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
The `viteEnvironment` field corresponde to the environment defined by the [Vite Environment API](https://vite.dev/guide/api-environment#environment-api). By default, Vite exposes `client` (for the browser) and `ssr` (for the server) environments.
|
||||||
|
:::
|
||||||
|
|
||||||
|
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).
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
jsdom environment exposes `jsdom` global variable equal to the current [JSDOM](https://github.com/jsdom/jsdom) instance. If you want TypeScript to recognize it, you can add `vitest/jsdom` to your `tsconfig.json` when you use this environment:
|
||||||
|
|
||||||
|
```json [tsconfig.json]
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"types": ["vitest/jsdom"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
:::
|
||||||
34
docs/config/environmentoptions.md
Normal file
34
docs/config/environmentoptions.md
Normal file
@ -0,0 +1,34 @@
|
|||||||
|
---
|
||||||
|
title: environmentOptions | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# environmentOptions
|
||||||
|
|
||||||
|
- **Type:** `Record<'jsdom' | 'happyDOM' | string, unknown>`
|
||||||
|
- **Default:** `{}`
|
||||||
|
|
||||||
|
These options are passed to the setup method of the current [environment](/config/environment). By default, you can configure options only for `jsdom` and `happyDOM` when you use them as your test environment.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```js [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
environmentOptions: {
|
||||||
|
jsdom: {
|
||||||
|
url: 'http://localhost:3000',
|
||||||
|
},
|
||||||
|
happyDOM: {
|
||||||
|
width: 300,
|
||||||
|
height: 400,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
Options are scoped to their environment. For example, put jsdom options under the `jsdom` key and happy-dom options under the `happyDOM` key. This lets you mix multiple environments within the same project.
|
||||||
|
:::
|
||||||
53
docs/config/exclude.md
Normal file
53
docs/config/exclude.md
Normal file
@ -0,0 +1,53 @@
|
|||||||
|
---
|
||||||
|
title: exclude | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# exclude
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** `['**/node_modules/**', '**/.git/**']`
|
||||||
|
- **CLI:** `vitest --exclude "**/excluded-file" --exclude "*/other-files/*.js"`
|
||||||
|
|
||||||
|
A list of [glob patterns](https://superchupu.dev/tinyglobby/comparison) that should be excluded from your test files. These patterns are resolved relative to the [`root`](/config/root) ([`process.cwd()`](https://nodejs.org/api/process.html#processcwd) by default).
|
||||||
|
|
||||||
|
Vitest uses the [`tinyglobby`](https://www.npmjs.com/package/tinyglobby) package to resolve the globs.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
This option does not affect coverage. If you need to remove certain files from the coverage report, use [`coverage.exclude`](/config/coverage#exclude).
|
||||||
|
|
||||||
|
This is the only option that doesn't override your configuration if you provide it with a CLI flag. All glob patterns added via `--exclude` flag will be added to the config's `exclude`.
|
||||||
|
:::
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
exclude: [
|
||||||
|
'**/node_modules/**',
|
||||||
|
'**/dist/**',
|
||||||
|
'./temp/**',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
Although the CLI `exclude` option is additive, manually setting `exclude` in your config will replace the default value. To extend the default `exclude` patterns, use `configDefaults` from `vitest/config`:
|
||||||
|
|
||||||
|
```js{6}
|
||||||
|
import { configDefaults, defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
exclude: [
|
||||||
|
...configDefaults.exclude,
|
||||||
|
'packages/template/*',
|
||||||
|
'./temp/**',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
:::
|
||||||
15
docs/config/execargv.md
Normal file
15
docs/config/execargv.md
Normal file
@ -0,0 +1,15 @@
|
|||||||
|
---
|
||||||
|
title: execArgv | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# execArgv
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** `[]`
|
||||||
|
|
||||||
|
Pass additional arguments to `node` in the runner worker. See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
|
||||||
|
|
||||||
|
:::warning
|
||||||
|
Be careful when using, it as some options may crash worker, e.g. `--prof`, `--title`. See https://github.com/nodejs/node/issues/41103.
|
||||||
|
:::
|
||||||
12
docs/config/expandsnapshotdiff.md
Normal file
12
docs/config/expandsnapshotdiff.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: expandSnapshotDiff | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# expandSnapshotDiff
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **CLI:** `--expandSnapshotDiff`, `--expand-snapshot-diff`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Show full diff when snapshot fails instead of a patch.
|
||||||
43
docs/config/expect.md
Normal file
43
docs/config/expect.md
Normal file
@ -0,0 +1,43 @@
|
|||||||
|
---
|
||||||
|
title: expect | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# expect
|
||||||
|
|
||||||
|
- **Type:** `ExpectOptions`
|
||||||
|
|
||||||
|
## expect.requireAssertions
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
The same as calling [`expect.hasAssertions()`](/api/expect#expect-hasassertions) at the start of every test. This makes sure that no test will pass accidentally.
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
This only works with Vitest's `expect`. If you use `assert` or `.should` assertions, they will not count, and your test will fail due to the lack of expect assertions.
|
||||||
|
|
||||||
|
You can change the value of this by calling `vi.setConfig({ expect: { requireAssertions: false } })`. The config will be applied to every subsequent `expect` call until the `vi.resetConfig` is called manually.
|
||||||
|
:::
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
When you run tests with `sequence.concurrent` and `expect.requireAssertions` set to `true`, you should use [local expect](/guide/test-context.html#expect) instead of the global one. Otherwise, this may cause false negatives in [some situations (#8469)](https://github.com/vitest-dev/vitest/issues/8469).
|
||||||
|
:::
|
||||||
|
|
||||||
|
## expect.poll
|
||||||
|
|
||||||
|
Global configuration options for [`expect.poll`](/api/expect#poll). These are the same options you can pass down to `expect.poll(condition, options)`.
|
||||||
|
|
||||||
|
### expect.poll.interval
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `50`
|
||||||
|
|
||||||
|
Polling interval in milliseconds
|
||||||
|
|
||||||
|
### expect.poll.timeout
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `1000`
|
||||||
|
|
||||||
|
Polling timeout in milliseconds
|
||||||
56
docs/config/faketimers.md
Normal file
56
docs/config/faketimers.md
Normal file
@ -0,0 +1,56 @@
|
|||||||
|
---
|
||||||
|
title: fakeTimers | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# fakeTimers
|
||||||
|
|
||||||
|
- **Type:** `FakeTimerInstallOpts`
|
||||||
|
|
||||||
|
Options that Vitest will pass down to [`@sinon/fake-timers`](https://www.npmjs.com/package/@sinonjs/fake-timers) when using [`vi.useFakeTimers()`](/api/vi#vi-usefaketimers).
|
||||||
|
|
||||||
|
## fakeTimers.now
|
||||||
|
|
||||||
|
- **Type:** `number | Date`
|
||||||
|
- **Default:** `Date.now()`
|
||||||
|
|
||||||
|
Installs fake timers with the specified Unix epoch.
|
||||||
|
|
||||||
|
## fakeTimers.toFake
|
||||||
|
|
||||||
|
- **Type:** `('setTimeout' | 'clearTimeout' | 'setImmediate' | 'clearImmediate' | 'setInterval' | 'clearInterval' | 'Date' | 'nextTick' | 'hrtime' | 'requestAnimationFrame' | 'cancelAnimationFrame' | 'requestIdleCallback' | 'cancelIdleCallback' | 'performance' | 'queueMicrotask')[]`
|
||||||
|
- **Default:** everything available globally except `nextTick` and `queueMicrotask`
|
||||||
|
|
||||||
|
An array with names of global methods and APIs to fake.
|
||||||
|
|
||||||
|
To only mock `setTimeout()` and `nextTick()`, specify this property as `['setTimeout', 'nextTick']`.
|
||||||
|
|
||||||
|
Mocking `nextTick` is not supported when running Vitest inside `node:child_process` by using `--pool=forks`. NodeJS uses `process.nextTick` internally in `node:child_process` and hangs when it is mocked. Mocking `nextTick` is supported when running Vitest with `--pool=threads`.
|
||||||
|
|
||||||
|
## fakeTimers.loopLimit
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `10_000`
|
||||||
|
|
||||||
|
The maximum number of timers that will be run when calling [`vi.runAllTimers()`](/api/vi#vi-runalltimers).
|
||||||
|
|
||||||
|
## fakeTimers.shouldAdvanceTime
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Tells @sinonjs/fake-timers to increment mocked time automatically based on the real system time shift (e.g. the mocked time will be incremented by 20ms for every 20ms change in the real system time).
|
||||||
|
|
||||||
|
## fakeTimers.advanceTimeDelta
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `20`
|
||||||
|
|
||||||
|
Relevant only when using with `shouldAdvanceTime: true`. increment mocked time by advanceTimeDelta ms every advanceTimeDelta ms change in the real system time.
|
||||||
|
|
||||||
|
## fakeTimers.shouldClearNativeTimers
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
|
||||||
|
Tells fake timers to clear "native" (i.e. not fake) timers by delegating to their respective handlers. When disabled, it can lead to potentially unexpected behavior if timers existed prior to starting fake timers session.
|
||||||
16
docs/config/fileparallelism.md
Normal file
16
docs/config/fileparallelism.md
Normal file
@ -0,0 +1,16 @@
|
|||||||
|
---
|
||||||
|
title: fileParallelism | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# fileParallelism
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
- **CLI:** `--no-file-parallelism`, `--fileParallelism=false`
|
||||||
|
|
||||||
|
Should all test files run in parallel. Setting this to `false` will override `maxWorkers` option to `1`.
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
This option doesn't affect tests running in the same file. If you want to run those in parallel, use `concurrent` option on [describe](/api/#describe-concurrent) or via [a config](#sequence-concurrent).
|
||||||
|
:::
|
||||||
24
docs/config/forcereruntriggers.md
Normal file
24
docs/config/forcereruntriggers.md
Normal file
@ -0,0 +1,24 @@
|
|||||||
|
---
|
||||||
|
title: forceRerunTriggers | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# forceRerunTriggers <CRoot />
|
||||||
|
|
||||||
|
- **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 [`server.watch.ignored`](https://vitejs.dev/config/server-options.html#server-watch).
|
||||||
|
:::
|
||||||
46
docs/config/globals.md
Normal file
46
docs/config/globals.md
Normal file
@ -0,0 +1,46 @@
|
|||||||
|
---
|
||||||
|
title: globals | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# globals
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
- **CLI:** `--globals`, `--no-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.
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
globals: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
Note that some libraries, e.g., `@testing-library/react`, rely on globals being present to perform auto cleanup.
|
||||||
|
:::
|
||||||
|
|
||||||
|
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 have redefined your [`typeRoots`](https://www.typescriptlang.org/tsconfig/#typeRoots) to include additional types in your compilation, you will need to add back the `node_modules` to make `vitest/globals` discoverable:
|
||||||
|
|
||||||
|
```json [tsconfig.json]
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"typeRoots": ["./types", "./node_modules/@types", "./node_modules"],
|
||||||
|
"types": ["vitest/globals"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
67
docs/config/globalsetup.md
Normal file
67
docs/config/globalsetup.md
Normal file
@ -0,0 +1,67 @@
|
|||||||
|
---
|
||||||
|
title: globalSetup | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# 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
|
||||||
|
Global setup runs only if there is at least one running test. This means that global setup might start running during watch mode after test file is changed (the test file will wait for global setup to finish before running).
|
||||||
|
|
||||||
|
Beware that the global setup is running in a different global scope, so your tests don't have access to variables defined here. However, you can pass down serializable data to tests via [`provide`](#provide) method:
|
||||||
|
|
||||||
|
:::code-group
|
||||||
|
```ts [example.test.js]
|
||||||
|
import { inject } from 'vitest'
|
||||||
|
|
||||||
|
inject('wsPort') === 3000
|
||||||
|
```
|
||||||
|
```ts [globalSetup.ts <Version>3.0.0</Version>]
|
||||||
|
import type { TestProject } from 'vitest/node'
|
||||||
|
|
||||||
|
export default function setup(project: TestProject) {
|
||||||
|
project.provide('wsPort', 3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module 'vitest' {
|
||||||
|
export interface ProvidedContext {
|
||||||
|
wsPort: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```ts [globalSetup.ts <Version>2.0.0</Version>]
|
||||||
|
import type { GlobalSetupContext } from 'vitest/node'
|
||||||
|
|
||||||
|
export default function setup({ provide }: GlobalSetupContext) {
|
||||||
|
provide('wsPort', 3000)
|
||||||
|
}
|
||||||
|
|
||||||
|
declare module 'vitest' {
|
||||||
|
export interface ProvidedContext {
|
||||||
|
wsPort: number
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
:::
|
||||||
|
|
||||||
|
Since Vitest 3, you can define a custom callback function to be called when Vitest reruns tests. If the function is asynchronous, the runner will wait for it to complete before executing tests. Note that you cannot destruct the `project` like `{ onTestsRerun }` because it relies on the context.
|
||||||
|
|
||||||
|
```ts [globalSetup.ts]
|
||||||
|
import type { TestProject } from 'vitest/node'
|
||||||
|
|
||||||
|
export default function setup(project: TestProject) {
|
||||||
|
project.onTestsRerun(async () => {
|
||||||
|
await restartDb()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
12
docs/config/hideskippedtests.md
Normal file
12
docs/config/hideskippedtests.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: hideSkippedTests | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# hideSkippedTests
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **CLI:** `--hideSkippedTests`, `--hide-skipped-tests`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Hide logs for skipped tests
|
||||||
12
docs/config/hooktimeout.md
Normal file
12
docs/config/hooktimeout.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: hookTimeout | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# hookTimeout
|
||||||
|
|
||||||
|
- **Type:** `number`
|
||||||
|
- **Default:** `10_000` in Node.js, `30_000` if `browser.enabled` is `true`
|
||||||
|
- **CLI:** `--hook-timeout=10000`, `--hookTimeout=10000`
|
||||||
|
|
||||||
|
Default timeout of a hook in milliseconds. Use `0` to disable timeout completely.
|
||||||
119
docs/config/include-source.md
Normal file
119
docs/config/include-source.md
Normal file
@ -0,0 +1,119 @@
|
|||||||
|
---
|
||||||
|
title: includeSource | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# includeSource
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** `[]`
|
||||||
|
|
||||||
|
A list of [glob patterns](https://superchupu.dev/tinyglobby/comparison) that match your [in-source test files](/guide/in-source). These patterns are resolved relative to the [`root`](/config/root) ([`process.cwd()`](https://nodejs.org/api/process.html#processcwd) by default).
|
||||||
|
|
||||||
|
When defined, Vitest will run all matched files that have `import.meta.vitest` inside.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
Vitest performs a simple text-based inclusion check on source files. If a file contains `import.meta.vitest`, even in a comment, it will be matched as an in-source test file.
|
||||||
|
:::
|
||||||
|
|
||||||
|
Vitest uses the [`tinyglobby`](https://www.npmjs.com/package/tinyglobby) package to resolve the globs.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
includeSource: ['src/**/*.{js,ts}'],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Then you can write tests inside your source files:
|
||||||
|
|
||||||
|
```ts [src/index.ts]
|
||||||
|
export function add(...args: number[]) {
|
||||||
|
return args.reduce((a, b) => a + b, 0)
|
||||||
|
}
|
||||||
|
|
||||||
|
// #region in-source test suites
|
||||||
|
if (import.meta.vitest) {
|
||||||
|
const { it, expect } = import.meta.vitest
|
||||||
|
it('add', () => {
|
||||||
|
expect(add()).toBe(0)
|
||||||
|
expect(add(1)).toBe(1)
|
||||||
|
expect(add(1, 2, 3)).toBe(6)
|
||||||
|
})
|
||||||
|
}
|
||||||
|
// #endregion
|
||||||
|
```
|
||||||
|
|
||||||
|
For your production build, you need to replace the `import.meta.vitest` with `undefined`, letting the bundler do the dead code elimination.
|
||||||
|
|
||||||
|
::: code-group
|
||||||
|
```js [vite.config.ts]
|
||||||
|
import { defineConfig } from 'vite'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
define: { // [!code ++]
|
||||||
|
'import.meta.vitest': 'undefined', // [!code ++]
|
||||||
|
}, // [!code ++]
|
||||||
|
})
|
||||||
|
```
|
||||||
|
```js [rolldown.config.js]
|
||||||
|
import { defineConfig } from 'rolldown/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
transform: {
|
||||||
|
define: { // [!code ++]
|
||||||
|
'import.meta.vitest': 'undefined', // [!code ++]
|
||||||
|
}, // [!code ++]
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
```js [rollup.config.js]
|
||||||
|
import replace from '@rollup/plugin-replace' // [!code ++]
|
||||||
|
|
||||||
|
export default {
|
||||||
|
plugins: [
|
||||||
|
replace({ // [!code ++]
|
||||||
|
'import.meta.vitest': 'undefined', // [!code ++]
|
||||||
|
}) // [!code ++]
|
||||||
|
],
|
||||||
|
// other options
|
||||||
|
}
|
||||||
|
```
|
||||||
|
```js [build.config.js]
|
||||||
|
import { defineBuildConfig } from 'unbuild'
|
||||||
|
|
||||||
|
export default defineBuildConfig({
|
||||||
|
replace: { // [!code ++]
|
||||||
|
'import.meta.vitest': 'undefined', // [!code ++]
|
||||||
|
}, // [!code ++]
|
||||||
|
// other options
|
||||||
|
})
|
||||||
|
```
|
||||||
|
```js [webpack.config.js]
|
||||||
|
const webpack = require('webpack')
|
||||||
|
|
||||||
|
module.exports = {
|
||||||
|
plugins: [
|
||||||
|
new webpack.DefinePlugin({ // [!code ++]
|
||||||
|
'import.meta.vitest': 'undefined', // [!code ++]
|
||||||
|
})// [!code ++]
|
||||||
|
],
|
||||||
|
}
|
||||||
|
```
|
||||||
|
:::
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
To get TypeScript support for `import.meta.vitest`, add `vitest/importMeta` to your `tsconfig.json`:
|
||||||
|
|
||||||
|
```json [tsconfig.json]
|
||||||
|
{
|
||||||
|
"compilerOptions": {
|
||||||
|
"types": ["vitest/importMeta"]
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
:::
|
||||||
71
docs/config/include.md
Normal file
71
docs/config/include.md
Normal file
@ -0,0 +1,71 @@
|
|||||||
|
---
|
||||||
|
title: include | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# include
|
||||||
|
|
||||||
|
- **Type:** `string[]`
|
||||||
|
- **Default:** `['**/*.{test,spec}.?(c|m)[jt]s?(x)']`
|
||||||
|
- **CLI:** `vitest [...include]`, `vitest **/*.test.js`
|
||||||
|
|
||||||
|
A list of [glob patterns](https://superchupu.dev/tinyglobby/comparison) that match your test files. These patterns are resolved relative to the [`root`](/config/root) ([`process.cwd()`](https://nodejs.org/api/process.html#processcwd) by default).
|
||||||
|
|
||||||
|
Vitest uses the [`tinyglobby`](https://www.npmjs.com/package/tinyglobby) package to resolve the globs.
|
||||||
|
|
||||||
|
::: tip NOTE
|
||||||
|
When using coverage, Vitest automatically adds test files `include` patterns to coverage's default `exclude` patterns. See [`coverage.exclude`](/config/coverage#exclude).
|
||||||
|
:::
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```js
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
include: [
|
||||||
|
'./test',
|
||||||
|
'./**/*.{test,spec}.tsx?',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
Vitest provides reasonable defaults, so normally you wouldn't override them. A good example of defining `include` is for [test projects](/guide/projects):
|
||||||
|
|
||||||
|
```js{8,12} [vitest.config.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'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
This option will override Vitest defaults. If you just want to extend them, use `configDefaults` from `vitest/config`:
|
||||||
|
|
||||||
|
```js{6}
|
||||||
|
import { configDefaults, defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
include: [
|
||||||
|
...configDefaults.include,
|
||||||
|
'./test',
|
||||||
|
'./**/*.{test,spec}.tsx?',
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
:::
|
||||||
22
docs/config/includetasklocation.md
Normal file
22
docs/config/includetasklocation.md
Normal file
@ -0,0 +1,22 @@
|
|||||||
|
---
|
||||||
|
title: includeTaskLocation | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# includeTaskLocation
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Should `location` property be included when Vitest API receives tasks in [reporters](#reporters). If you have a lot of tests, this might cause a small performance regression.
|
||||||
|
|
||||||
|
The `location` property has `column` and `line` values that correspond to the `test` or `describe` position in the original file.
|
||||||
|
|
||||||
|
This option will be auto-enabled if you don't disable it explicitly, and you are running Vitest with:
|
||||||
|
- [Vitest UI](/guide/ui)
|
||||||
|
- or using the [Browser Mode](/guide/browser/) without [headless](/guide/browser/#headless) mode
|
||||||
|
- or using [HTML Reporter](/guide/reporters#html-reporter)
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
This option has no effect if you do not use custom code that relies on this.
|
||||||
|
:::
|
||||||
2194
docs/config/index.md
2194
docs/config/index.md
File diff suppressed because it is too large
Load Diff
18
docs/config/isolate.md
Normal file
18
docs/config/isolate.md
Normal file
@ -0,0 +1,18 @@
|
|||||||
|
---
|
||||||
|
title: isolate | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# isolate
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `true`
|
||||||
|
- **CLI:** `--no-isolate`, `--isolate=false`
|
||||||
|
|
||||||
|
Run tests in an isolated environment. This option has no effect on `vmThreads` and `vmForks` pools.
|
||||||
|
|
||||||
|
Disabling this option might [improve performance](/guide/improving-performance) if your code doesn't rely on side effects (which is usually true for projects with `node` environment).
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
You can disable isolation for specific test files by using Vitest workspaces and disabling isolation per project.
|
||||||
|
:::
|
||||||
12
docs/config/logheapusage.md
Normal file
12
docs/config/logheapusage.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: logHeapUsage | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# logHeapUsage
|
||||||
|
|
||||||
|
- **Type**: `boolean`
|
||||||
|
- **Default**: `false`
|
||||||
|
- **CLI:** `--logHeapUsage`, `--logHeapUsage=false`
|
||||||
|
|
||||||
|
Show heap usage after each test. Useful for debugging memory leaks.
|
||||||
14
docs/config/maxconcurrency.md
Normal file
14
docs/config/maxconcurrency.md
Normal file
@ -0,0 +1,14 @@
|
|||||||
|
---
|
||||||
|
title: maxConcurrency | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# maxConcurrency
|
||||||
|
|
||||||
|
- **Type**: `number`
|
||||||
|
- **Default**: `5`
|
||||||
|
- **CLI**: `--max-concurrency=10`, `--maxConcurrency=10`
|
||||||
|
|
||||||
|
A number of tests that are allowed to run at the same time marked with `test.concurrent`.
|
||||||
|
|
||||||
|
Test above this limit will be queued to run when available slot appears.
|
||||||
54
docs/config/maxworkers.md
Normal file
54
docs/config/maxworkers.md
Normal file
@ -0,0 +1,54 @@
|
|||||||
|
---
|
||||||
|
title: maxWorkers | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# maxWorkers
|
||||||
|
|
||||||
|
- **Type:** `number | string`
|
||||||
|
- **Default:**
|
||||||
|
- if [`watch`](/config/watch) is disabled, uses all available parallelism
|
||||||
|
- if [`watch`](/config/watch) is enabled, uses half of all available parallelism
|
||||||
|
|
||||||
|
Defines the maximum concurrency for test workers. Accepts either a number or a percentage string.
|
||||||
|
|
||||||
|
- Number: spawns up to the specified number of workers.
|
||||||
|
- Percentage string (e.g., "50%"): computes the worker count as the given percentage of the machine’s available parallelism.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
### Number
|
||||||
|
|
||||||
|
::: code-group
|
||||||
|
```js [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
maxWorkers: 4,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
```bash [CLI]
|
||||||
|
vitest --maxWorkers=4
|
||||||
|
```
|
||||||
|
:::
|
||||||
|
|
||||||
|
### Percent
|
||||||
|
|
||||||
|
::: code-group
|
||||||
|
```js [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
maxWorkers: '50%',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
```bash [CLI]
|
||||||
|
vitest --maxWorkers=50%
|
||||||
|
```
|
||||||
|
:::
|
||||||
|
|
||||||
|
Vitest uses [`os.availableParallelism`](https://nodejs.org/api/os.html#osavailableparallelism) to know the maximum amount of parallelism available.
|
||||||
23
docs/config/mockreset.md
Normal file
23
docs/config/mockreset.md
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
---
|
||||||
|
title: mockReset | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# mockReset
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `false`
|
||||||
|
|
||||||
|
Should Vitest automatically call [`vi.resetAllMocks()`](/api/vi#vi-resetallmocks) before each test.
|
||||||
|
|
||||||
|
This will clear mock history and reset each implementation.
|
||||||
|
|
||||||
|
```js [vitest.config.js]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
mockReset: true,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
12
docs/config/mode.md
Normal file
12
docs/config/mode.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: mode | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# mode
|
||||||
|
|
||||||
|
- **Type:** `string`
|
||||||
|
- **CLI:** `--mode=staging`
|
||||||
|
- **Default:** `'test'`
|
||||||
|
|
||||||
|
Overrides Vite mode
|
||||||
115
docs/config/name.md
Normal file
115
docs/config/name.md
Normal file
@ -0,0 +1,115 @@
|
|||||||
|
---
|
||||||
|
title: name | Config
|
||||||
|
---
|
||||||
|
|
||||||
|
# name
|
||||||
|
|
||||||
|
- **Type:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
interface UserConfig {
|
||||||
|
name?: string | { label: string; color?: LabelColor }
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
Assign a custom name to the test project or Vitest process. The name will be visible in the CLI and UI, and available in the Node.js API via [`project.name`](/api/advanced/test-project#name).
|
||||||
|
|
||||||
|
The color used by the CLI and UI can be changed by providing an object with a `color` property.
|
||||||
|
|
||||||
|
## Colors
|
||||||
|
|
||||||
|
The displayed colors depend on your terminal’s color scheme. In the UI, colors match their CSS equivalents.
|
||||||
|
|
||||||
|
- black
|
||||||
|
- red
|
||||||
|
- green
|
||||||
|
- yellow
|
||||||
|
- blue
|
||||||
|
- magenta
|
||||||
|
- cyan
|
||||||
|
- white
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
::: code-group
|
||||||
|
```js [string]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
name: 'unit',
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
```js [object]
|
||||||
|
import { defineConfig } from 'vitest/config'
|
||||||
|
|
||||||
|
export default defineConfig({
|
||||||
|
test: {
|
||||||
|
name: {
|
||||||
|
label: 'unit',
|
||||||
|
color: 'blue',
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
:::
|
||||||
|
|
||||||
|
This property is mostly useful if you have several projects as it helps distinguish them in your terminal:
|
||||||
|
|
||||||
|
```js{7,11} [vitest.config.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'],
|
||||||
|
},
|
||||||
|
],
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
Vitest automatically assigns a name when none is provided. Resolution order:
|
||||||
|
|
||||||
|
- If the project is specified by a config file or directory, Vitest uses the package.json's `name` field.
|
||||||
|
- If there is no `package.json`, Vitest falls back to the project folder's basename.
|
||||||
|
- If the project is defined inline in the `projects` array (an object), Vitest assigns a numeric name equal to that project's array index (0-based).
|
||||||
|
:::
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
Note that projects cannot have the same name. Vitest will throw an error during the config resolution.
|
||||||
|
:::
|
||||||
|
|
||||||
|
You can also assign different names to different browser [instances](/config/browser/instances):
|
||||||
|
|
||||||
|
```js{10,11} [vitest.config.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' },
|
||||||
|
],
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
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.
|
||||||
|
:::
|
||||||
30
docs/config/onconsolelog.md
Normal file
30
docs/config/onconsolelog.md
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
---
|
||||||
|
title: onConsoleLog | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# onConsoleLog <CRoot />
|
||||||
|
|
||||||
|
```ts
|
||||||
|
function onConsoleLog(
|
||||||
|
log: string,
|
||||||
|
type: 'stdout' | 'stderr',
|
||||||
|
entity: TestModule | TestSuite | TestCase | undefined,
|
||||||
|
): boolean | void
|
||||||
|
```
|
||||||
|
|
||||||
|
Custom handler for `console` methods in tests. If you return `false`, Vitest will not print the log to the console. Note that Vitest ignores all other falsy values.
|
||||||
|
|
||||||
|
Can be useful for filtering out logs from third-party libraries.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
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')
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
37
docs/config/onstacktrace.md
Normal file
37
docs/config/onstacktrace.md
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
---
|
||||||
|
title: onStackTrace | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# onStackTrace <CRoot />
|
||||||
|
|
||||||
|
- **Type**: `(error: Error, frame: ParsedStack) => boolean | void`
|
||||||
|
|
||||||
|
Apply a filtering function to each frame of each stack trace when handling errors. This does not apply to stack traces printed by [`printConsoleTrace`](#printConsoleTrace). The first argument, `error`, is a `TestError`.
|
||||||
|
|
||||||
|
Can be useful for filtering out stack trace frames from third-party libraries.
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
The stack trace's total size is also typically limited by V8's [`Error.stackTraceLimit`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/stackTraceLimit) number. You could set this to a high value in your test setup function to prevent stacks from being truncated.
|
||||||
|
:::
|
||||||
|
|
||||||
|
```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
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
40
docs/config/onunhandlederror.md
Normal file
40
docs/config/onunhandlederror.md
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
---
|
||||||
|
title: onUnhandledError | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# onUnhandledError <CRoot /> <Version>4.0.0</Version>
|
||||||
|
|
||||||
|
- **Type:**
|
||||||
|
|
||||||
|
```ts
|
||||||
|
function onUnhandledError(
|
||||||
|
error: (TestError | Error) & { type: string }
|
||||||
|
): boolean | void
|
||||||
|
```
|
||||||
|
|
||||||
|
A custom callback for filtering unhandled errors that should not be reported. When an error is filtered out, it no longer affects the result of the test run.
|
||||||
|
|
||||||
|
To report unhandled errors without affecting the test outcome, use the [`dangerouslyIgnoreUnhandledErrors`](/config/dangerouslyignoreunhandlederrors) option instead.
|
||||||
|
|
||||||
|
::: tip
|
||||||
|
This callback is called on the main thread, it doesn't have access to your test context.
|
||||||
|
:::
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```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
|
||||||
|
}
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
|
```
|
||||||
12
docs/config/open.md
Normal file
12
docs/config/open.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: open | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# open <CRoot />
|
||||||
|
|
||||||
|
- **Type:** `boolean`
|
||||||
|
- **Default:** `!process.env.CI`
|
||||||
|
- **CLI:** `--open`, `--open=false`
|
||||||
|
|
||||||
|
Open Vitest UI automatically if it's [enabled](/config/ui).
|
||||||
12
docs/config/outputfile.md
Normal file
12
docs/config/outputfile.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: outputFile | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# outputFile <CRoot /> {#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.
|
||||||
12
docs/config/passwithnotests.md
Normal file
12
docs/config/passwithnotests.md
Normal file
@ -0,0 +1,12 @@
|
|||||||
|
---
|
||||||
|
title: passWithNoTests | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# passWithNoTests <CRoot />
|
||||||
|
|
||||||
|
- **Type**: `boolean`
|
||||||
|
- **Default**: `false`
|
||||||
|
- **CLI:** `--passWithNoTests`, `--passWithNoTests=false`
|
||||||
|
|
||||||
|
Vitest will not fail, if no tests will be found.
|
||||||
50
docs/config/pool.md
Normal file
50
docs/config/pool.md
Normal file
@ -0,0 +1,50 @@
|
|||||||
|
---
|
||||||
|
title: pool | Config
|
||||||
|
outline: deep
|
||||||
|
---
|
||||||
|
|
||||||
|
# pool
|
||||||
|
|
||||||
|
- **Type:** `'threads' | 'forks' | 'vmThreads' | 'vmForks'`
|
||||||
|
- **Default:** `'forks'`
|
||||||
|
- **CLI:** `--pool=threads`
|
||||||
|
|
||||||
|
Pool used to run tests in.
|
||||||
|
|
||||||
|
## threads
|
||||||
|
|
||||||
|
Enable multi-threading. When using threads you are unable to use process related APIs such as `process.chdir()`. Some libraries written in native languages, such as Prisma, `bcrypt` and `canvas`, have problems when running in multiple threads and run into segfaults. In these cases it is advised to use `forks` pool instead.
|
||||||
|
|
||||||
|
## forks
|
||||||
|
|
||||||
|
Similar as `threads` pool but uses `child_process` instead of `worker_threads`. Communication between tests and main process is not as fast as with `threads` pool. Process related APIs such as `process.chdir()` are available in `forks` pool.
|
||||||
|
|
||||||
|
## vmThreads
|
||||||
|
|
||||||
|
Run tests using [VM context](https://nodejs.org/api/vm.html) (inside a sandboxed environment) in a `threads` pool.
|
||||||
|
|
||||||
|
This makes tests run faster, but the VM module is unstable when running [ESM code](https://github.com/nodejs/node/issues/37648). Your tests will [leak memory](https://github.com/nodejs/node/issues/33439) - to battle that, consider manually editing [`vmMemoryLimit`](#vmMemorylimit) value.
|
||||||
|
|
||||||
|
::: warning
|
||||||
|
Running code in a sandbox has some advantages (faster tests), but also comes with a number of disadvantages.
|
||||||
|
|
||||||
|
- The globals within native modules, such as (`fs`, `path`, etc), differ from the globals present in your test environment. As a result, any error thrown by these native modules will reference a different Error constructor compared to the one used in your code:
|
||||||
|
|
||||||
|
```ts
|
||||||
|
try {
|
||||||
|
fs.writeFileSync('/doesnt exist')
|
||||||
|
}
|
||||||
|
catch (err) {
|
||||||
|
console.log(err instanceof Error) // false
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
- Importing ES modules caches them indefinitely which introduces memory leaks if you have a lot of contexts (test files). There is no API in Node.js that clears that cache.
|
||||||
|
- Accessing globals [takes longer](https://github.com/nodejs/node/issues/31658) in a sandbox environment.
|
||||||
|
|
||||||
|
Please, be aware of these issues when using this option. Vitest team cannot fix any of the issues on our side.
|
||||||
|
:::
|
||||||
|
|
||||||
|
## vmForks
|
||||||
|
|
||||||
|
Similar as `vmThreads` pool but uses `child_process` instead of `worker_threads`. Communication between tests and the main process is not as fast as with `vmThreads` pool. Process related APIs such as `process.chdir()` are available in `vmForks` pool. Please be aware that this pool has the same pitfalls listed in `vmThreads`.
|
||||||
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user