From 65292c365584efa71b6a837ac24967aeaa77f9bb Mon Sep 17 00:00:00 2001 From: Vladimir Date: Thu, 6 Nov 2025 14:59:05 +0100 Subject: [PATCH] docs: update structure (#8625) --- docs/.vitepress/components.d.ts | 3 +- docs/.vitepress/components/CRoot.vue | 5 + docs/.vitepress/components/Deprecated.vue | 8 +- docs/.vitepress/components/Experimental.vue | 5 + .../components/NonProjectOption.vue | 10 - docs/.vitepress/config.ts | 1195 ++++++--- docs/.vitepress/scripts/cli-generator.ts | 11 +- docs/.vitepress/theme/index.ts | 25 +- .../api => api/advanced}/import-example.md | 0 docs/{ => api}/advanced/metadata.md | 2 +- docs/{advanced/api => api/advanced}/plugin.md | 2 +- .../api => api/advanced}/reporters.md | 34 +- docs/{ => api}/advanced/runner.md | 4 +- .../api => api/advanced}/test-case.md | 12 +- .../api => api/advanced}/test-collection.md | 2 +- .../api => api/advanced}/test-module.md | 8 +- .../api => api/advanced}/test-project.md | 14 +- .../advanced}/test-specification.md | 8 +- .../api => api/advanced}/test-suite.md | 18 +- docs/{advanced/api => api/advanced}/vitest.md | 28 +- .../browser/assertions.md} | 6 +- docs/{guide => api}/browser/commands.md | 2 +- docs/{guide => api}/browser/context.md | 8 +- .../browser/interactivity.md} | 0 docs/{guide => api}/browser/locators.md | 28 +- docs/api/index.md | 6 +- docs/api/vi.md | 2 +- docs/blog/vitest-3-2.md | 4 +- docs/blog/vitest-3.md | 4 +- docs/blog/vitest-4.md | 22 +- docs/config/alias.md | 18 + docs/config/allowonly.md | 37 + docs/config/api.md | 12 + docs/config/attachmentsdir.md | 11 + docs/config/bail.md | 14 + docs/config/benchmark.md | 70 + .../browser/config.md => config/browser.md} | 21 +- docs/config/browser/api.md | 12 + docs/config/browser/commands.md | 11 + docs/config/browser/connecttimeout.md | 15 + docs/config/browser/enabled.md | 44 + docs/config/browser/expect.md | 255 ++ docs/config/browser/headless.md | 12 + docs/config/browser/instances.md | 52 + docs/config/browser/isolate.md | 16 + docs/config/browser/locators.md | 15 + docs/config/browser/orchestratorscripts.md | 44 + docs/{guide => config}/browser/playwright.md | 6 +- docs/{guide => config}/browser/preview.md | 6 +- docs/config/browser/provider.md | 86 + docs/config/browser/screenshotdirectory.md | 11 + docs/config/browser/screenshotfailures.md | 11 + docs/config/browser/testerhtmlpath.md | 10 + docs/config/browser/trace.md | 48 + docs/config/browser/trackunhandlederrors.md | 15 + docs/config/browser/ui.md | 12 + docs/config/browser/viewport.md | 11 + docs/{guide => config}/browser/webdriverio.md | 4 +- docs/config/cache.md | 31 + docs/config/chaiconfig.md | 34 + docs/config/clearmocks.md | 23 + docs/config/coverage.md | 397 +++ docs/config/css.md | 52 + .../dangerouslyignoreunhandlederrors.md | 28 + docs/config/deps.md | 132 + docs/config/diff.md | 99 + docs/config/dir.md | 12 + docs/config/disableconsoleintercept.md | 20 + docs/config/env.md | 10 + docs/config/environment.md | 100 + docs/config/environmentoptions.md | 34 + docs/config/exclude.md | 53 + docs/config/execargv.md | 15 + docs/config/expandsnapshotdiff.md | 12 + docs/config/expect.md | 43 + docs/config/faketimers.md | 56 + docs/config/fileparallelism.md | 16 + docs/config/forcereruntriggers.md | 24 + docs/config/globals.md | 46 + docs/config/globalsetup.md | 67 + docs/config/hideskippedtests.md | 12 + docs/config/hooktimeout.md | 12 + docs/config/include-source.md | 119 + docs/config/include.md | 71 + docs/config/includetasklocation.md | 22 + docs/config/index.md | 2194 +---------------- docs/config/isolate.md | 18 + docs/config/logheapusage.md | 12 + docs/config/maxconcurrency.md | 14 + docs/config/maxworkers.md | 54 + docs/config/mockreset.md | 23 + docs/config/mode.md | 12 + docs/config/name.md | 115 + docs/config/onconsolelog.md | 30 + docs/config/onstacktrace.md | 37 + docs/config/onunhandlederror.md | 40 + docs/config/open.md | 12 + docs/config/outputfile.md | 12 + docs/config/passwithnotests.md | 12 + docs/config/pool.md | 50 + docs/config/printconsoletrace.md | 11 + docs/config/projects.md | 11 + docs/config/provide.md | 50 + docs/config/reporters.md | 72 + docs/config/resolvesnapshotpath.md | 21 + docs/config/restoremocks.md | 23 + docs/config/retry.md | 12 + docs/config/root.md | 11 + docs/config/runner.md | 11 + docs/config/sequence.md | 163 ++ docs/config/server.md | 95 + docs/config/setupfiles.md | 39 + docs/config/silent.md | 14 + docs/config/slowtestthreshold.md | 12 + docs/config/snapshotenvironment.md | 32 + docs/config/snapshotformat.md | 16 + docs/config/snapshotserializers.md | 11 + docs/config/teardowntimeout.md | 12 + docs/config/testnamepattern.md | 26 + docs/config/testtimeout.md | 12 + docs/config/typecheck.md | 82 + docs/config/ui.md | 16 + docs/config/unstubenvs.md | 21 + docs/config/unstubglobals.md | 21 + docs/config/update.md | 12 + docs/config/vmmemorylimit.md | 35 + docs/config/watch.md | 16 + docs/config/watchtriggerpatterns.md | 34 + .../{advanced/api => guide/advanced}/index.md | 12 +- docs/{ => guide}/advanced/pool.md | 2 +- docs/{ => guide}/advanced/reporters.md | 2 +- .../guide => guide/advanced}/tests.md | 10 +- docs/guide/browser/component-testing.md | 6 +- docs/guide/browser/index.md | 10 +- docs/guide/browser/multiple-setups.md | 2 +- docs/guide/browser/trace-view.md | 4 +- .../browser/visual-regression-testing.md | 4 +- docs/guide/cli-generated.md | 202 +- docs/guide/in-source.md | 52 +- docs/guide/index.md | 2 +- docs/guide/migration.md | 12 +- docs/guide/projects.md | 2 +- docs/guide/reporters.md | 2 +- docs/guide/snapshot.md | 2 +- docs/guide/test-annotations.md | 2 +- docs/guide/test-context.md | 2 +- eslint.config.js | 2 +- netlify.toml | 40 + packages/browser/context.d.ts | 70 +- packages/browser/jest-dom.d.ts | 58 +- packages/vitest/src/node/cli/cli-config.ts | 4 +- .../vitest/src/node/config/resolveConfig.ts | 2 +- packages/vitest/src/node/types/browser.ts | 4 +- packages/vitest/src/node/types/config.ts | 3 +- 154 files changed, 4982 insertions(+), 2952 deletions(-) create mode 100644 docs/.vitepress/components/CRoot.vue create mode 100644 docs/.vitepress/components/Experimental.vue delete mode 100644 docs/.vitepress/components/NonProjectOption.vue rename docs/{advanced/api => api/advanced}/import-example.md (100%) rename docs/{ => api}/advanced/metadata.md (98%) rename docs/{advanced/api => api/advanced}/plugin.md (98%) rename docs/{advanced/api => api/advanced}/reporters.md (88%) rename docs/{ => api}/advanced/runner.md (98%) rename docs/{advanced/api => api/advanced}/test-case.md (90%) rename docs/{advanced/api => api/advanced}/test-collection.md (97%) rename docs/{advanced/api => api/advanced}/test-module.md (89%) rename docs/{advanced/api => api/advanced}/test-project.md (92%) rename docs/{advanced/api => api/advanced}/test-specification.md (90%) rename docs/{advanced/api => api/advanced}/test-suite.md (87%) rename docs/{advanced/api => api/advanced}/vitest.md (94%) rename docs/{guide/browser/assertion-api.md => api/browser/assertions.md} (99%) rename docs/{guide => api}/browser/commands.md (96%) rename docs/{guide => api}/browser/context.md (95%) rename docs/{guide/browser/interactivity-api.md => api/browser/interactivity.md} (100%) rename docs/{guide => api}/browser/locators.md (95%) create mode 100644 docs/config/alias.md create mode 100644 docs/config/allowonly.md create mode 100644 docs/config/api.md create mode 100644 docs/config/attachmentsdir.md create mode 100644 docs/config/bail.md create mode 100644 docs/config/benchmark.md rename docs/{guide/browser/config.md => config/browser.md} (95%) create mode 100644 docs/config/browser/api.md create mode 100644 docs/config/browser/commands.md create mode 100644 docs/config/browser/connecttimeout.md create mode 100644 docs/config/browser/enabled.md create mode 100644 docs/config/browser/expect.md create mode 100644 docs/config/browser/headless.md create mode 100644 docs/config/browser/instances.md create mode 100644 docs/config/browser/isolate.md create mode 100644 docs/config/browser/locators.md create mode 100644 docs/config/browser/orchestratorscripts.md rename docs/{guide => config}/browser/playwright.md (92%) rename docs/{guide => config}/browser/preview.md (80%) create mode 100644 docs/config/browser/provider.md create mode 100644 docs/config/browser/screenshotdirectory.md create mode 100644 docs/config/browser/screenshotfailures.md create mode 100644 docs/config/browser/testerhtmlpath.md create mode 100644 docs/config/browser/trace.md create mode 100644 docs/config/browser/trackunhandlederrors.md create mode 100644 docs/config/browser/ui.md create mode 100644 docs/config/browser/viewport.md rename docs/{guide => config}/browser/webdriverio.md (91%) create mode 100644 docs/config/cache.md create mode 100644 docs/config/chaiconfig.md create mode 100644 docs/config/clearmocks.md create mode 100644 docs/config/coverage.md create mode 100644 docs/config/css.md create mode 100644 docs/config/dangerouslyignoreunhandlederrors.md create mode 100644 docs/config/deps.md create mode 100644 docs/config/diff.md create mode 100644 docs/config/dir.md create mode 100644 docs/config/disableconsoleintercept.md create mode 100644 docs/config/env.md create mode 100644 docs/config/environment.md create mode 100644 docs/config/environmentoptions.md create mode 100644 docs/config/exclude.md create mode 100644 docs/config/execargv.md create mode 100644 docs/config/expandsnapshotdiff.md create mode 100644 docs/config/expect.md create mode 100644 docs/config/faketimers.md create mode 100644 docs/config/fileparallelism.md create mode 100644 docs/config/forcereruntriggers.md create mode 100644 docs/config/globals.md create mode 100644 docs/config/globalsetup.md create mode 100644 docs/config/hideskippedtests.md create mode 100644 docs/config/hooktimeout.md create mode 100644 docs/config/include-source.md create mode 100644 docs/config/include.md create mode 100644 docs/config/includetasklocation.md create mode 100644 docs/config/isolate.md create mode 100644 docs/config/logheapusage.md create mode 100644 docs/config/maxconcurrency.md create mode 100644 docs/config/maxworkers.md create mode 100644 docs/config/mockreset.md create mode 100644 docs/config/mode.md create mode 100644 docs/config/name.md create mode 100644 docs/config/onconsolelog.md create mode 100644 docs/config/onstacktrace.md create mode 100644 docs/config/onunhandlederror.md create mode 100644 docs/config/open.md create mode 100644 docs/config/outputfile.md create mode 100644 docs/config/passwithnotests.md create mode 100644 docs/config/pool.md create mode 100644 docs/config/printconsoletrace.md create mode 100644 docs/config/projects.md create mode 100644 docs/config/provide.md create mode 100644 docs/config/reporters.md create mode 100644 docs/config/resolvesnapshotpath.md create mode 100644 docs/config/restoremocks.md create mode 100644 docs/config/retry.md create mode 100644 docs/config/root.md create mode 100644 docs/config/runner.md create mode 100644 docs/config/sequence.md create mode 100644 docs/config/server.md create mode 100644 docs/config/setupfiles.md create mode 100644 docs/config/silent.md create mode 100644 docs/config/slowtestthreshold.md create mode 100644 docs/config/snapshotenvironment.md create mode 100644 docs/config/snapshotformat.md create mode 100644 docs/config/snapshotserializers.md create mode 100644 docs/config/teardowntimeout.md create mode 100644 docs/config/testnamepattern.md create mode 100644 docs/config/testtimeout.md create mode 100644 docs/config/typecheck.md create mode 100644 docs/config/ui.md create mode 100644 docs/config/unstubenvs.md create mode 100644 docs/config/unstubglobals.md create mode 100644 docs/config/update.md create mode 100644 docs/config/vmmemorylimit.md create mode 100644 docs/config/watch.md create mode 100644 docs/config/watchtriggerpatterns.md rename docs/{advanced/api => guide/advanced}/index.md (91%) rename docs/{ => guide}/advanced/pool.md (98%) rename docs/{ => guide}/advanced/reporters.md (96%) rename docs/{advanced/guide => guide/advanced}/tests.md (89%) diff --git a/docs/.vitepress/components.d.ts b/docs/.vitepress/components.d.ts index a6c6b9087..6d19e0f7d 100644 --- a/docs/.vitepress/components.d.ts +++ b/docs/.vitepress/components.d.ts @@ -12,11 +12,12 @@ declare module 'vue' { Box: typeof import('./components/Box.vue')['default'] Contributors: typeof import('./components/Contributors.vue')['default'] CourseLink: typeof import('./components/CourseLink.vue')['default'] + CRoot: typeof import('./components/CRoot.vue')['default'] Deprecated: typeof import('./components/Deprecated.vue')['default'] + Experimental: typeof import('./components/Experimental.vue')['default'] FeaturesList: typeof import('./components/FeaturesList.vue')['default'] HomePage: typeof import('./components/HomePage.vue')['default'] ListItem: typeof import('./components/ListItem.vue')['default'] - NonProjectOption: typeof import('./components/NonProjectOption.vue')['default'] Version: typeof import('./components/Version.vue')['default'] } } diff --git a/docs/.vitepress/components/CRoot.vue b/docs/.vitepress/components/CRoot.vue new file mode 100644 index 000000000..31a5f0bfb --- /dev/null +++ b/docs/.vitepress/components/CRoot.vue @@ -0,0 +1,5 @@ + diff --git a/docs/.vitepress/components/Deprecated.vue b/docs/.vitepress/components/Deprecated.vue index b1983b8d2..9ae996276 100644 --- a/docs/.vitepress/components/Deprecated.vue +++ b/docs/.vitepress/components/Deprecated.vue @@ -1,9 +1,5 @@ - - diff --git a/docs/.vitepress/components/Experimental.vue b/docs/.vitepress/components/Experimental.vue new file mode 100644 index 000000000..18681c681 --- /dev/null +++ b/docs/.vitepress/components/Experimental.vue @@ -0,0 +1,5 @@ + diff --git a/docs/.vitepress/components/NonProjectOption.vue b/docs/.vitepress/components/NonProjectOption.vue deleted file mode 100644 index 87e1ae66d..000000000 --- a/docs/.vitepress/components/NonProjectOption.vue +++ /dev/null @@ -1,10 +0,0 @@ - diff --git a/docs/.vitepress/config.ts b/docs/.vitepress/config.ts index c375cbb88..41924c593 100644 --- a/docs/.vitepress/config.ts +++ b/docs/.vitepress/config.ts @@ -1,7 +1,6 @@ import { transformerTwoslash } from '@shikijs/vitepress-twoslash' import { transformerNotationWordHighlight } from '@shikijs/transformers' import { withPwa } from '@vite-pwa/vitepress' -import type { DefaultTheme } from 'vitepress' import { defineConfig } from 'vitepress' import { tabsMarkdownPlugin } from 'vitepress-plugin-tabs' import { @@ -148,30 +147,12 @@ export default ({ mode }: { mode: string }) => { }, nav: [ - { text: 'Guide & API', link: '/guide/', activeMatch: '^/(guide|api)/(?!browser)' }, + { text: 'Guides', link: '/guide/', activeMatch: '^/guide/' }, + { text: 'API', link: '/api/', activeMatch: '^/api/' }, { text: 'Config', link: '/config/', activeMatch: '^/config/' }, - { text: 'Browser Mode', link: '/guide/browser', activeMatch: '^/guide/browser/' }, { - text: 'Resources', - items: [ - { - text: 'Advanced API', - link: '/advanced/api/', - activeMatch: '^/advanced/', - }, - { - items: [ - { - text: 'Blog', - link: '/blog', - }, - { - text: 'Team', - link: '/team', - }, - ], - }, - ], + text: 'Blog', + link: '/blog', }, { text: `v${version}`, @@ -190,6 +171,10 @@ export default ({ mode }: { mode: string }) => { text: 'Contributing', link: contributing, }, + { + text: 'Team', + link: '/team', + }, ], }, { @@ -221,10 +206,473 @@ export default ({ mode }: { mode: string }) => { ], sidebar: { - '/guide/browser': [ + '/config': [ + { + text: 'Config Reference', + collapsed: false, + items: [ + { + text: 'Config File', + link: '/config/', + }, + { + text: 'include', + link: '/config/include', + }, + { + text: 'exclude', + link: '/config/exclude', + }, + { + text: 'includeSource', + link: '/config/include-source', + }, + { + text: 'name', + link: '/config/name', + }, + { + text: 'server', + link: '/config/server', + }, + { + text: 'deps', + link: '/config/deps', + }, + { + text: 'runner', + link: '/config/runner', + }, + { + text: 'benchmark', + link: '/config/benchmark', + }, + { + text: 'alias', + link: '/config/alias', + }, + { + text: 'globals', + link: '/config/globals', + }, + { + text: 'environment', + link: '/config/environment', + }, + { + text: 'environmentOptions', + link: '/config/environmentoptions', + }, + { + text: 'watch', + link: '/config/watch', + }, + { + text: 'watchTriggerPatterns', + link: '/config/watchtriggerpatterns', + }, + { + text: 'root', + link: '/config/root', + }, + { + text: 'dir', + link: '/config/dir', + }, + { + text: 'reporters', + link: '/config/reporters', + }, + { + text: 'outputFile', + link: '/config/outputfile', + }, + { + text: 'pool', + link: '/config/pool', + }, + { + text: 'execArgv', + link: '/config/execargv', + }, + { + text: 'vmMemoryLimit', + link: '/config/vmmemorylimit', + }, + { + text: 'fileParallelism', + link: '/config/fileparallelism', + }, + { + text: 'maxWorkers', + link: '/config/maxworkers', + }, + { + text: 'testTimeout', + link: '/config/testtimeout', + }, + { + text: 'hookTimeout', + link: '/config/hooktimeout', + }, + { + text: 'teardownTimeout', + link: '/config/teardowntimeout', + }, + { + text: 'silent', + link: '/config/silent', + }, + { + text: 'setupFiles', + link: '/config/setupfiles', + }, + { + text: 'provide', + link: '/config/provide', + }, + { + text: 'globalSetup', + link: '/config/globalsetup', + }, + { + text: 'forceRerunTriggers', + link: '/config/forcereruntriggers', + }, + { + text: 'coverage', + link: '/config/coverage', + }, + { + text: 'testNamePattern', + link: '/config/testnamepattern', + }, + { + text: 'ui', + link: '/config/ui', + }, + { + text: 'open', + link: '/config/open', + }, + { + text: 'api', + link: '/config/api', + }, + { + text: 'clearMocks', + link: '/config/clearmocks', + }, + { + text: 'mockReset', + link: '/config/mockreset', + }, + { + text: 'restoreMocks', + link: '/config/restoremocks', + }, + { + text: 'unstubEnvs', + link: '/config/unstubenvs', + }, + { + text: 'unstubGlobals', + link: '/config/unstubglobals', + }, + { + text: 'snapshotFormat', + link: '/config/snapshotformat', + }, + { + text: 'snapshotSerializers', + link: '/config/snapshotserializers', + }, + { + text: 'resolveSnapshotPath', + link: '/config/resolvesnapshotpath', + }, + { + text: 'allowOnly', + link: '/config/allowonly', + }, + { + text: 'passWithNoTests', + link: '/config/passwithnotests', + }, + { + text: 'logHeapUsage', + link: '/config/logheapusage', + }, + { + text: 'css', + link: '/config/css', + }, + { + text: 'maxConcurrency', + link: '/config/maxconcurrency', + }, + { + text: 'cache', + link: '/config/cache', + }, + { + text: 'sequence', + link: '/config/sequence', + }, + { + text: 'typecheck', + link: '/config/typecheck', + }, + { + text: 'slowTestThreshold', + link: '/config/slowtestthreshold', + }, + { + text: 'chaiConfig', + link: '/config/chaiconfig', + }, + { + text: 'bail', + link: '/config/bail', + }, + { + text: 'retry', + link: '/config/retry', + }, + { + text: 'onConsoleLog', + link: '/config/onconsolelog', + }, + { + text: 'onStackTrace', + link: '/config/onstacktrace', + }, + { + text: 'onUnhandledError', + link: '/config/onunhandlederror', + }, + { + text: 'dangerouslyIgnoreUnhandled...', + link: '/config/dangerouslyignoreunhandlederrors', + }, + { + text: 'diff', + link: '/config/diff', + }, + { + text: 'fakeTimers', + link: '/config/faketimers', + }, + { + text: 'projects', + link: '/config/projects', + }, + { + text: 'isolate', + link: '/config/isolate', + }, + { + text: 'includeTaskLocation', + link: '/config/includetasklocation', + }, + { + text: 'snapshotEnvironment', + link: '/config/snapshotenvironment', + }, + { + text: 'env', + link: '/config/env', + }, + { + text: 'expect', + link: '/config/expect', + }, + { + text: 'printConsoleTrace', + link: '/config/printconsoletrace', + }, + { + text: 'attachmentsDir', + link: '/config/attachmentsdir', + }, + { + text: 'hideSkippedTests', + link: '/config/hideskippedtests', + }, + { + text: 'mode', + link: '/config/mode', + }, + { + text: 'expandSnapshotDiff', + link: '/config/expandsnapshotdiff', + }, + { + text: 'disableConsoleIntercept', + link: '/config/disableconsoleintercept', + }, + ], + }, + { + text: 'Browser Mode', + collapsed: false, + items: [ + { + text: 'Providers', + collapsed: false, + items: [ + { + text: 'playwright', + link: '/config/browser/playwright', + }, + { + text: 'webdriverio', + link: '/config/browser/webdriverio', + }, + { + text: 'preview', + link: '/config/browser/preview', + }, + ], + }, + // { + // text: 'Render Function', + // collapsed: true, + // items: [ + // { + // text: 'react', + // link: '/config/browser/react', + // }, + // { + // text: 'vue', + // link: '/config/browser/vue', + // }, + // { + // text: 'svelte', + // link: '/config/browser/svelte', + // }, + // ], + // }, + { + text: 'browser.enabled', + link: '/config/browser/enabled', + }, + { + text: 'browser.instances', + link: '/config/browser/instances', + }, + { + text: 'browser.headless', + link: '/config/browser/headless', + }, + { + text: 'browser.isolate', + link: '/config/browser/isolate', + }, + { + text: 'browser.testerHtmlPath', + link: '/config/browser/testerhtmlpath', + }, + { + text: 'browser.api', + link: '/config/browser/api', + }, + { + text: 'browser.provider', + link: '/config/browser/provider', + }, + { + text: 'browser.ui', + link: '/config/browser/ui', + }, + { + text: 'browser.viewport', + link: '/config/browser/viewport', + }, + { + text: 'browser.locators', + link: '/config/browser/locators', + }, + { + text: 'browser.screenshotDirectory', + link: '/config/browser/screenshotdirectory', + }, + { + text: 'browser.screenshotFailures', + link: '/config/browser/screenshotfailures', + }, + { + text: 'browser.orchestratorScripts', + link: '/config/browser/orchestratorscripts', + }, + { + text: 'browser.commands', + link: '/config/browser/commands', + }, + { + text: 'browser.connectTimeout', + link: '/config/browser/connecttimeout', + }, + { + text: 'browser.trace', + link: '/config/browser/trace', + }, + { + text: 'browser.trackUnhandledErrors', + link: '/config/browser/trackunhandlederrors', + }, + { + text: 'browser.expect', + link: '/config/browser/expect', + }, + ], + }, + // { + // text: '@vitest/plugin-eslint', + // collapsed: true, + // items: [ + // { + // text: 'Lints', + // link: '/config/eslint', + // }, + // // TODO: generate + // { + // text: 'consistent-test-filename', + // link: '/config/eslint/consistent-test-filename', + // }, + // { + // text: 'consistent-test-it', + // link: '/config/eslint/consistent-test-it', + // }, + // ], + // }, + // { + // text: 'vscode', + // link: '/config/vscode', + // }, + ], + '/guide': [ { text: 'Introduction', collapsed: false, + items: [ + { + text: 'Why Vitest', + link: '/guide/why', + }, + { + text: 'Getting Started', + link: '/guide/', + }, + { + text: 'Features', + link: '/guide/features', + }, + ], + }, + { + text: 'Browser Mode', + collapsed: false, items: [ { text: 'Why Browser Mode', @@ -236,69 +684,6 @@ export default ({ mode }: { mode: string }) => { link: '/guide/browser/', docFooterText: 'Getting Started | Browser Mode', }, - ], - }, - { - text: 'Configuration', - collapsed: false, - items: [ - { - text: 'Browser Config Reference', - link: '/guide/browser/config', - docFooterText: 'Browser Config Reference | Browser Mode', - }, - { - text: 'Configuring Playwright', - link: '/guide/browser/playwright', - docFooterText: 'Configuring Playwright | Browser Mode', - }, - { - text: 'Configuring WebdriverIO', - link: '/guide/browser/webdriverio', - docFooterText: 'Configuring WebdriverIO | Browser Mode', - }, - { - text: 'Configuring Preview', - link: '/guide/browser/preview', - docFooterText: 'Configuring Preview | Browser Mode', - }, - ], - }, - { - text: 'API', - collapsed: false, - items: [ - { - text: 'Context API', - link: '/guide/browser/context', - docFooterText: 'Context API | Browser Mode', - }, - { - text: 'Interactivity API', - link: '/guide/browser/interactivity-api', - docFooterText: 'Interactivity API | Browser Mode', - }, - { - text: 'Locators', - link: '/guide/browser/locators', - docFooterText: 'Locators | Browser Mode', - }, - { - text: 'Assertion API', - link: '/guide/browser/assertion-api', - docFooterText: 'Assertion API | Browser Mode', - }, - { - text: 'Commands API', - link: '/guide/browser/commands', - docFooterText: 'Commands | Browser Mode', - }, - ], - }, - { - text: 'Guides', - collapsed: false, - items: [ { text: 'Multiple Setups', link: '/guide/browser/multiple-setups', @@ -321,137 +706,361 @@ export default ({ mode }: { mode: string }) => { }, ], }, - { - items: [ - ...footer(), - { - text: 'Node API Reference', - link: '/advanced/api/', - }, - ], - }, - ], - '/advanced': [ - { - text: 'API', - collapsed: false, - items: [ - { - text: 'Node API', - items: [ - { - text: 'Getting Started', - link: '/advanced/api/', - }, - { - text: 'Vitest', - link: '/advanced/api/vitest', - }, - { - text: 'TestProject', - link: '/advanced/api/test-project', - }, - { - text: 'TestSpecification', - link: '/advanced/api/test-specification', - }, - ], - }, - { - text: 'Test Task API', - items: [ - { - text: 'TestCase', - link: '/advanced/api/test-case', - }, - { - text: 'TestSuite', - link: '/advanced/api/test-suite', - }, - { - text: 'TestModule', - link: '/advanced/api/test-module', - }, - { - text: 'TestCollection', - link: '/advanced/api/test-collection', - }, - ], - }, - { - text: 'Plugin API', - link: '/advanced/api/plugin', - }, - { - text: 'Runner API', - link: '/advanced/runner', - }, - { - text: 'Reporters API', - link: '/advanced/api/reporters', - }, - { - text: 'Task Metadata', - link: '/advanced/metadata', - }, - ], - }, { text: 'Guides', collapsed: false, items: [ { - text: 'Running Tests', - link: '/advanced/guide/tests', + text: 'CLI', + link: '/guide/cli', + }, + { + text: 'Test Filtering', + link: '/guide/filtering', + }, + { + text: 'Test Context', + link: '/guide/test-context', + }, + { + text: 'Test Environment', + link: '/guide/environment', + }, + { + text: 'Snapshot', + link: '/guide/snapshot', + }, + { + text: 'Mocking', + link: '/guide/mocking', + collapsed: true, + items: [ + { + text: 'Mocking Dates', + link: '/guide/mocking/dates', + }, + { + text: 'Mocking Functions', + link: '/guide/mocking/functions', + }, + { + text: 'Mocking Globals', + link: '/guide/mocking/globals', + }, + { + text: 'Mocking Modules', + link: '/guide/mocking/modules', + }, + { + text: 'Mocking the File System', + link: '/guide/mocking/file-system', + }, + { + text: 'Mocking Requests', + link: '/guide/mocking/requests', + }, + { + text: 'Mocking Timers', + link: '/guide/mocking/timers', + }, + { + text: 'Mocking Classes', + link: '/guide/mocking/classes', + }, + ], + }, + { + text: 'Parallelism', + link: '/guide/parallelism', + }, + { + text: 'Test Projects', + link: '/guide/projects', + }, + { + text: 'Reporters', + link: '/guide/reporters', + }, + { + text: 'Coverage', + link: '/guide/coverage', + }, + { + text: 'Testing Types', + link: '/guide/testing-types', + }, + { + text: 'Vitest UI', + link: '/guide/ui', + }, + { + text: 'In-Source Testing', + link: '/guide/in-source', + }, + { + text: 'Test Annotations', + link: '/guide/test-annotations', + }, + { + text: 'Extending Matchers', + link: '/guide/extending-matchers', + }, + { + text: 'IDE Integration', + link: '/guide/ide', + }, + { + text: 'Debugging', + link: '/guide/debugging', + }, + { + text: 'Common Errors', + link: '/guide/common-errors', + }, + { + text: 'Migration Guide', + link: '/guide/migration', + collapsed: false, + items: [ + { + text: 'Migrating to Vitest 4.0', + link: '/guide/migration#vitest-4', + }, + { + text: 'Migrating from Jest', + link: '/guide/migration#jest', + }, + ], + }, + { + text: 'Performance', + collapsed: false, + items: [ + { + text: 'Profiling Test Performance', + link: '/guide/profiling-test-performance', + }, + { + text: 'Improving Performance', + link: '/guide/improving-performance', + }, + ], + }, + { + text: 'Recipes', + link: '/guide/recipes', + }, + ], + }, + { + text: 'Advanced', + collapsed: true, + items: [ + { + text: 'Getting Started', + link: '/guide/advanced/', + }, + { + text: 'Running Tests via API', + link: '/guide/advanced/tests', }, { text: 'Extending Reporters', - link: '/advanced/reporters', + link: '/guide/advanced/reporters', }, { text: 'Custom Pool', - link: '/advanced/pool', + link: '/guide/advanced/pool', }, ], }, - { - items: footer(), - }, ], - '/team': [], - '/blog': [], - '/': [ + '/api': [ { - text: 'Introduction', - collapsed: false, - items: introduction(), + text: 'Test API Reference', + link: '/api/', }, { - text: 'API', - collapsed: false, - items: api(), + text: 'Mocks', + link: '/api/mock', }, { - text: 'Guides', - collapsed: false, - items: guide(), + text: 'Vi Utility', + link: '/api/vi', }, { + text: 'Expect', + link: '/api/expect', + }, + { + text: 'ExpectTypeOf', + link: '/api/expect-typeof', + }, + { + text: 'Assert', + link: '/api/assert', + }, + { + text: 'AssertType', + link: '/api/assert-type', + }, + { + text: 'Browser Mode', items: [ { - text: 'Browser Mode', - link: '/guide/browser', + text: 'Context', + link: '/api/browser/context', }, { - text: 'Node API Reference', - link: '/advanced/api', + text: 'Interactivity', + link: '/api/browser/interactivity', }, { - text: 'Comparisons', - link: '/guide/comparisons', + text: 'Locators', + link: '/api/browser/locators', + }, + { + text: 'Assertions', + link: '/api/browser/assertions', + }, + { + text: 'Commands', + link: '/api/browser/commands', }, ], }, + { + text: 'Advanced', + collapsed: true, + items: [ + { + text: 'Vitest', + link: '/api/advanced/vitest', + }, + { + text: 'TestProject', + link: '/api/advanced/test-project', + }, + { + text: 'TestSpecification', + link: '/api/advanced/test-specification', + }, + { + text: 'TestCase', + link: '/api/advanced/test-case', + }, + { + text: 'TestSuite', + link: '/api/advanced/test-suite', + }, + { + text: 'TestModule', + link: '/api/advanced/test-module', + }, + { + text: 'TestCollection', + link: '/api/advanced/test-collection', + }, + { + text: 'VitestPlugin', + link: '/api/advanced/plugin', + }, + { + text: 'VitestRunner', + link: '/api/advanced/runner', + }, + { + text: 'Reporter', + link: '/api/advanced/reporters', + }, + { + text: 'TaskMeta', + link: '/api/advanced/metadata', + }, + ], + }, + // { + // text: 'Text Runner', + // collapsed: false, + // items: [ + // // TODO: generate + // { + // text: 'test', + // link: '/api/test', + // }, + // { + // text: 'describe', + // link: '/api/describe', + // }, + // { + // text: 'beforeEach', + // link: '/api/before-each', + // }, + // { + // text: 'afterEach', + // link: '/api/after-each', + // }, + // ], + // }, + // { + // text: 'Assertion API', + // collapsed: false, + // items: [ + // { + // text: 'expect', + // link: '/api/expect', + // }, + // { + // text: 'assert', + // link: '/api/assert', + // }, + // { + // text: 'expectTypeOf', + // link: '/api/expect-typeof', + // }, + // { + // text: 'assertType', + // link: '/api/assert-type', + // }, + // ], + // }, + // { + // text: 'Vi Utility API', + // collapsed: false, + // items: [ + // { + // text: 'Mock Modules', + // link: '/api/vi/mock-modiles', + // }, + // { + // text: 'Mock Functions', + // link: '/api/vi/mock-functions', + // }, + // { + // text: 'Mock Timers', + // link: '/api/vi/mock-timers', + // }, + // { + // text: 'Miscellaneous', + // link: '/api/vi/miscellaneous', + // }, + // ], + // }, + // { + // text: 'Browser Mode', + // collapsed: false, + // items: [ + // // TODO: generate + // { + // text: 'page', + // link: '/api/browser/page', + // }, + // { + // text: 'locators', + // link: '/api/browser/locators', + // }, + // ], + // }, ], }, }, @@ -459,215 +1068,3 @@ export default ({ mode }: { mode: string }) => { transformHead, })) } - -function footer(): DefaultTheme.SidebarItem[] { - return [ - { - text: 'Config Reference', - link: '/config/', - }, - { - text: 'Test API Reference', - link: '/api/', - }, - ] -} - -function introduction(): DefaultTheme.SidebarItem[] { - return [ - { - text: 'Why Vitest', - link: '/guide/why', - }, - { - text: 'Getting Started', - link: '/guide/', - }, - { - text: 'Features', - link: '/guide/features', - }, - { - text: 'Config Reference', - link: '/config/', - }, - ] -} - -function guide(): DefaultTheme.SidebarItem[] { - return [ - { - text: 'CLI', - link: '/guide/cli', - }, - { - text: 'Test Filtering', - link: '/guide/filtering', - }, - { - text: 'Test Projects', - link: '/guide/projects', - }, - { - text: 'Reporters', - link: '/guide/reporters', - }, - { - text: 'Coverage', - link: '/guide/coverage', - }, - { - text: 'Snapshot', - link: '/guide/snapshot', - }, - { - text: 'Mocking', - link: '/guide/mocking', - collapsed: true, - items: [ - { - text: 'Mocking Dates', - link: '/guide/mocking/dates', - }, - { - text: 'Mocking Functions', - link: '/guide/mocking/functions', - }, - { - text: 'Mocking Globals', - link: '/guide/mocking/globals', - }, - { - text: 'Mocking Modules', - link: '/guide/mocking/modules', - }, - { - text: 'Mocking the File System', - link: '/guide/mocking/file-system', - }, - { - text: 'Mocking Requests', - link: '/guide/mocking/requests', - }, - { - text: 'Mocking Timers', - link: '/guide/mocking/timers', - }, - { - text: 'Mocking Classes', - link: '/guide/mocking/classes', - }, - ], - }, - { - text: 'Parallelism', - link: '/guide/parallelism', - }, - { - text: 'Testing Types', - link: '/guide/testing-types', - }, - { - text: 'Vitest UI', - link: '/guide/ui', - }, - { - text: 'In-Source Testing', - link: '/guide/in-source', - }, - { - text: 'Test Context', - link: '/guide/test-context', - }, - { - text: 'Test Annotations', - link: '/guide/test-annotations', - }, - { - text: 'Environment', - link: '/guide/environment', - }, - { - text: 'Extending Matchers', - link: '/guide/extending-matchers', - }, - { - text: 'IDE Integration', - link: '/guide/ide', - }, - { - text: 'Debugging', - link: '/guide/debugging', - }, - { - text: 'Common Errors', - link: '/guide/common-errors', - }, - { - text: 'Migration Guide', - link: '/guide/migration', - collapsed: false, - items: [ - { - text: 'Migrating to Vitest 4.0', - link: '/guide/migration#vitest-4', - }, - { - text: 'Migrating from Jest', - link: '/guide/migration#jest', - }, - ], - }, - { - text: 'Performance', - collapsed: false, - items: [ - { - text: 'Profiling Test Performance', - link: '/guide/profiling-test-performance', - }, - { - text: 'Improving Performance', - link: '/guide/improving-performance', - }, - ], - }, - { - text: 'Recipes', - link: '/guide/recipes', - }, - ] -} - -function api(): DefaultTheme.SidebarItem[] { - return [ - { - text: 'Test API Reference', - link: '/api/', - }, - { - text: 'Mocks', - link: '/api/mock', - }, - { - text: 'Vi Utility', - link: '/api/vi', - }, - { - text: 'Expect', - link: '/api/expect', - }, - { - text: 'ExpectTypeOf', - link: '/api/expect-typeof', - }, - { - text: 'Assert', - link: '/api/assert', - }, - { - text: 'AssertType', - link: '/api/assert-type', - }, - ] -} diff --git a/docs/.vitepress/scripts/cli-generator.ts b/docs/.vitepress/scripts/cli-generator.ts index bea3ade8f..b0c4dcd6f 100644 --- a/docs/.vitepress/scripts/cli-generator.ts +++ b/docs/.vitepress/scripts/cli-generator.ts @@ -35,6 +35,12 @@ const skipConfig = new Set([ 'run', 'hideSkippedTests', 'dom', + 'inspect', + 'inspectBrk', + 'project', + 'ui', + 'browser.name', + 'browser.fileParallelism', ]) function resolveOptions(options: CLIOptions, parentName?: string) { @@ -76,8 +82,9 @@ const options = resolveOptions(cliOptionsConfig) const template = options.map((option) => { const title = option.title const cli = option.cli - const config = skipConfig.has(title) ? '' : `[${title}](${title.includes('browser.') ? '/guide/browser/config' : '/config/'}#${title.toLowerCase().replace(/\./g, '-')})` - return `### ${title}\n\n- **CLI:** ${cli}\n${config ? `- **Config:** ${config}\n` : ''}\n${option.description}\n` + const [page, ...hash] = (title.startsWith('browser.') ? title.slice(8) : title).toLowerCase().split('.') + 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') writeFileSync(cliTablePath, template, 'utf-8') diff --git a/docs/.vitepress/theme/index.ts b/docs/.vitepress/theme/index.ts index 2b089a692..10577d559 100644 --- a/docs/.vitepress/theme/index.ts +++ b/docs/.vitepress/theme/index.ts @@ -6,7 +6,9 @@ import { enhanceAppWithTabs } from 'vitepress-plugin-tabs/client' import { h } from 'vue' import HomePage from '../components/HomePage.vue' import Version from '../components/Version.vue' +import CRoot from '../components/CRoot.vue' import Deprecated from '../components/Deprecated.vue' +import Experimental from '../components/Experimental.vue' import '../style/main.css' import '../style/vars.css' import 'uno.css' @@ -24,8 +26,29 @@ export default { '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('CRoot', CRoot) + app.component('Experimental', Experimental) app.component('Deprecated', Deprecated) app.use(TwoslashFloatingVue) enhanceAppWithTabs(app) diff --git a/docs/advanced/api/import-example.md b/docs/api/advanced/import-example.md similarity index 100% rename from docs/advanced/api/import-example.md rename to docs/api/advanced/import-example.md diff --git a/docs/advanced/metadata.md b/docs/api/advanced/metadata.md similarity index 98% rename from docs/advanced/metadata.md rename to docs/api/advanced/metadata.md index b86faa64c..43dd41a0f 100644 --- a/docs/advanced/metadata.md +++ b/docs/api/advanced/metadata.md @@ -1,4 +1,4 @@ -# Task Metadata +# Task Metadata advanced 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. diff --git a/docs/advanced/api/plugin.md b/docs/api/advanced/plugin.md similarity index 98% rename from docs/advanced/api/plugin.md rename to docs/api/advanced/plugin.md index dd64a5fab..6620f14de 100644 --- a/docs/advanced/api/plugin.md +++ b/docs/api/advanced/plugin.md @@ -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 diff --git a/docs/advanced/api/reporters.md b/docs/api/advanced/reporters.md similarity index 88% rename from docs/advanced/api/reporters.md rename to docs/api/advanced/reporters.md index ba87fc346..90f4ddc39 100644 --- a/docs/advanced/api/reporters.md +++ b/docs/api/advanced/reporters.md @@ -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. -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] import { BaseReporter } from 'vitest/reporters' @@ -51,13 +51,13 @@ export default class CustomReporter extends BaseReporter { function onInit(vitest: Vitest): Awaitable ``` -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 -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 ```ts @@ -99,7 +99,7 @@ function onTestRunStart( ): Awaitable ``` -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. @@ -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. -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). @@ -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 - `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). @@ -210,7 +210,7 @@ If Vitest didn't perform any coverage, this hook is not called. function onTestModuleQueued(testModule: TestModule): Awaitable ``` -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 @@ -218,7 +218,7 @@ This method is called right before Vitest imports the setup file and the test mo function onTestModuleCollected(testModule: TestModule): Awaitable ``` -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 @@ -226,7 +226,7 @@ This method is called when all tests inside the file were collected, meaning [`t function onTestModuleStart(testModule: TestModule): Awaitable ``` -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 @@ -234,7 +234,7 @@ This method is called right after [`onTestModuleCollected`](#ontestmodulecollect function onTestModuleEnd(testModule: TestModule): Awaitable ``` -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 @@ -249,9 +249,9 @@ This method is called when any of these hooks have started running: - `beforeEach` - `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 `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` - `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 `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 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 -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 @@ -318,7 +318,7 @@ function onTestCaseResult(testCase: TestCase): Awaitable 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 3.2.0 {#ontestannotate} diff --git a/docs/advanced/runner.md b/docs/api/advanced/runner.md similarity index 98% rename from docs/advanced/runner.md rename to docs/api/advanced/runner.md index 91d6bdcb5..4b7d3fd49 100644 --- a/docs/advanced/runner.md +++ b/docs/api/advanced/runner.md @@ -1,4 +1,4 @@ -# Runner API +# Runner API advanced ::: 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. @@ -150,7 +150,7 @@ Snapshot support and some other features depend on the runner. If you don't want ## Tasks ::: 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. ::: diff --git a/docs/advanced/api/test-case.md b/docs/api/advanced/test-case.md similarity index 90% rename from docs/advanced/api/test-case.md rename to docs/api/advanced/test-case.md index 40fae5f57..3775db204 100644 --- a/docs/advanced/api/test-case.md +++ b/docs/api/advanced/test-case.md @@ -1,6 +1,6 @@ # 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: @@ -12,11 +12,11 @@ if (task.type === 'test') { ## 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 -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 @@ -49,7 +49,7 @@ describe('the validation logic', () => { ## 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: @@ -93,7 +93,7 @@ test('the validation works correctly', () => { ## 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 @@ -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 ``` -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} import { test } from 'vitest' diff --git a/docs/advanced/api/test-collection.md b/docs/api/advanced/test-collection.md similarity index 97% rename from docs/advanced/api/test-collection.md rename to docs/api/advanced/test-collection.md index 988f9d961..50e55a61e 100644 --- a/docs/advanced/api/test-collection.md +++ b/docs/api/advanced/test-collection.md @@ -1,6 +1,6 @@ # 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 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()]`. diff --git a/docs/advanced/api/test-module.md b/docs/api/advanced/test-module.md similarity index 89% rename from docs/advanced/api/test-module.md rename to docs/api/advanced/test-module.md index ba74f4629..95a3ae8da 100644 --- a/docs/advanced/api/test-module.md +++ b/docs/api/advanced/test-module.md @@ -1,6 +1,6 @@ # 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: @@ -11,7 +11,7 @@ if (task.type === 'module') { ``` ::: 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 @@ -40,7 +40,7 @@ Module id relative to the project. This is the same as `task.name` in the deprec 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 3.1.0 {#meta} @@ -48,7 +48,7 @@ Works the same way as [`testSuite.state()`](/advanced/api/test-suite#state), but 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} import { test } from 'vitest' diff --git a/docs/advanced/api/test-project.md b/docs/api/advanced/test-project.md similarity index 92% rename from docs/advanced/api/test-project.md rename to docs/api/advanced/test-project.md index 9fef2c8c1..72eff647a 100644 --- a/docs/advanced/api/test-project.md +++ b/docs/api/advanced/test-project.md @@ -51,12 +51,12 @@ export default defineConfig({ ::: ::: 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` references the global [`Vitest`](/advanced/api/vitest) process. +`vitest` references the global [`Vitest`](/api/advanced/vitest) process. ## serializedConfig @@ -78,7 +78,7 @@ project.serializedConfig === project.serializedConfig // ❌ ## 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 import type { ResolvedConfig } from 'vitest/node' @@ -179,7 +179,7 @@ function createSpecification( ): 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 import { createVitest } from 'vitest/node' @@ -195,7 +195,7 @@ await vitest.runTestSpecifications([specification]) ``` ::: 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. ::: @@ -225,7 +225,7 @@ function globTestFiles(filters?: string[]): { 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 project.globTestFiles(['foo']) // ✅ @@ -298,7 +298,7 @@ Internally, Vitest uses this method to import global setups, custom coverage pro 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 project.onTestsRerun((specs) => { diff --git a/docs/advanced/api/test-specification.md b/docs/api/advanced/test-specification.md similarity index 90% rename from docs/advanced/api/test-specification.md rename to docs/api/advanced/test-specification.md index ef1c2a108..020859f8f 100644 --- a/docs/advanced/api/test-specification.md +++ b/docs/api/advanced/test-specification.md @@ -2,7 +2,7 @@ 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 const specification = project.createSpecification( @@ -15,11 +15,11 @@ const specification = project.createSpecification( ## taskId -[Test module's](/advanced/api/test-suite#id) identifier. +[Test module's](/api/advanced/test-suite#id) identifier. ## 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 @@ -33,7 +33,7 @@ The ID of the module in Vite's module graph. Usually, it's an absolute file path ## 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 experimental {#pool} diff --git a/docs/advanced/api/test-suite.md b/docs/api/advanced/test-suite.md similarity index 87% rename from docs/advanced/api/test-suite.md rename to docs/api/advanced/test-suite.md index 6894178a5..db2f98e71 100644 --- a/docs/advanced/api/test-suite.md +++ b/docs/api/advanced/test-suite.md @@ -1,6 +1,6 @@ # 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: @@ -12,11 +12,11 @@ if (task.type === 'suite') { ## 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 -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 @@ -49,7 +49,7 @@ describe('the validation logic', () => { ## 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: @@ -94,7 +94,7 @@ describe('the validation works correctly', () => { ## 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 @@ -114,7 +114,7 @@ The options that suite was collected with. ## 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 for (const task of suite.children) { @@ -129,7 +129,7 @@ for (const task of suite.children) { ``` ::: 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 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. ::: 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 @@ -197,7 +197,7 @@ Note that errors are serialized into simple objects: `instanceof Error` will alw 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} import { test } from 'vitest' diff --git a/docs/advanced/api/vitest.md b/docs/api/advanced/vitest.md similarity index 94% rename from docs/advanced/api/vitest.md rename to docs/api/advanced/vitest.md index a17ff143b..b49fc3505 100644 --- a/docs/advanced/api/vitest.md +++ b/docs/api/advanced/vitest.md @@ -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. ::: -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 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 -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. @@ -132,7 +132,7 @@ declare module 'vitest' { ``` ::: 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 @@ -165,7 +165,7 @@ function globTestSpecifications( ): Promise ``` -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. @@ -187,7 +187,7 @@ function getRelevantTestSpecifications( ): Promise ``` -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 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. -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 @@ -214,9 +214,9 @@ This method is called automatically by [`startVitest`](/advanced/guide/tests) if function collect(filters?: string[]): Promise ``` -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 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 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 @@ -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 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 @@ -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. -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 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 ``` -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 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 ``` -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. @@ -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 3.1.0 {#matchesprojectfilter} diff --git a/docs/guide/browser/assertion-api.md b/docs/api/browser/assertions.md similarity index 99% rename from docs/guide/browser/assertion-api.md rename to docs/api/browser/assertions.md index 471bc61ba..953bb93a6 100644 --- a/docs/guide/browser/assertion-api.md +++ b/docs/api/browser/assertions.md @@ -300,7 +300,7 @@ await expect.element( ).toBeVisible() ``` -## toBeInViewport +## toBeInViewport 4.0.0 {#tobeinviewport} ```ts function toBeInViewport(options: { ratio?: number }): Promise @@ -1082,7 +1082,7 @@ function toMatchScreenshot( ::: tip 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 @@ -1194,7 +1194,7 @@ await expect.element(getByTestId('button')).toMatchScreenshot('fancy-button', { - `screenshotOptions: object` The same options allowed by - [`locator.screenshot()`](/guide/browser/locators.html#screenshot), except for: + [`locator.screenshot()`](/api/browser/locators.html#screenshot), except for: - `'base64'` - `'path'` diff --git a/docs/guide/browser/commands.md b/docs/api/browser/commands.md similarity index 96% rename from docs/guide/browser/commands.md rename to docs/api/browser/commands.md index 8e3704430..720af5e41 100644 --- a/docs/guide/browser/commands.md +++ b/docs/api/browser/commands.md @@ -61,7 +61,7 @@ CDP session works only with `playwright` provider and only when using `chromium` ## 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 import type { Plugin } from 'vitest/config' diff --git a/docs/guide/browser/context.md b/docs/api/browser/context.md similarity index 95% rename from docs/guide/browser/context.md rename to docs/api/browser/context.md index 8bedda3b1..8d093a5d3 100644 --- a/docs/guide/browser/context.md +++ b/docs/api/browser/context.md @@ -9,7 +9,7 @@ Vitest exposes a context module via `vitest/browser` entry point. As of 2.0, it ## `userEvent` ::: 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 @@ -43,7 +43,7 @@ export const userEvent: { ## `commands` ::: 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 @@ -61,7 +61,7 @@ The `page` export provides utilities to interact with the current `page`. ::: 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. -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 @@ -108,7 +108,7 @@ export const page: { ``` ::: 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 3.2.0 diff --git a/docs/guide/browser/interactivity-api.md b/docs/api/browser/interactivity.md similarity index 100% rename from docs/guide/browser/interactivity-api.md rename to docs/api/browser/interactivity.md diff --git a/docs/guide/browser/locators.md b/docs/api/browser/locators.md similarity index 95% rename from docs/guide/browser/locators.md rename to docs/api/browser/locators.md index fd801e3df..44e17f287 100644 --- a/docs/guide/browser/locators.md +++ b/docs/api/browser/locators.md @@ -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. -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 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 ``` -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
@@ -614,7 +614,7 @@ import { page } from 'vitest/browser' 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 @@ -630,7 +630,7 @@ import { page } from 'vitest/browser' 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 @@ -646,7 +646,7 @@ import { page } from 'vitest/browser' 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 @@ -662,7 +662,7 @@ import { page } from 'vitest/browser' 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 @@ -678,7 +678,7 @@ import { page } from 'vitest/browser' 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 @@ -694,7 +694,7 @@ import { page } from 'vitest/browser' 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 @@ -710,7 +710,7 @@ import { page } from 'vitest/browser' 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 @@ -732,7 +732,7 @@ const france = page.getByText('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 @@ -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 @@ -779,7 +779,7 @@ function screenshot(options?: LocatorScreenshotOptions & { base64?: false }): Pr 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. @@ -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. ::: 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 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. -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) diff --git a/docs/api/index.md b/docs/api/index.md index 49bf6d700..298a6b3bb 100644 --- a/docs/api/index.md +++ b/docs/api/index.md @@ -429,8 +429,6 @@ You can also access Object attributes with `.`, if you are using objects as argu // ✓ 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 `|`; * 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 `|`; * 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. ::: 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 diff --git a/docs/api/vi.md b/docs/api/vi.md index 2ef0c70ce..6d5563edd 100644 --- a/docs/api/vi.md +++ b/docs/api/vi.md @@ -850,7 +850,7 @@ await vi.advanceTimersToNextTimerAsync() // log: 3 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 let frameRendered = false diff --git a/docs/blog/vitest-3-2.md b/docs/blog/vitest-3-2.md index 772e8239e..f05592a75 100644 --- a/docs/blog/vitest-3-2.md +++ b/docs/blog/vitest-3-2.md @@ -110,7 +110,7 @@ export default defineConfig({ ## 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 import { locators } from '@vitest/browser/context' @@ -172,7 +172,7 @@ locators.extend({ 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` diff --git a/docs/blog/vitest-3.md b/docs/blog/vitest-3.md index 455f6589f..0e655f6a0 100644 --- a/docs/blog/vitest-3.md +++ b/docs/blog/vitest-3.md @@ -62,7 +62,7 @@ For the latest news about the Vitest ecosystem and Vitest core, follow us on [Bl
-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. @@ -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. -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 diff --git a/docs/blog/vitest-4.md b/docs/blog/vitest-4.md index 7aa5e2ca4..9ee0512b6 100644 --- a/docs/blog/vitest-4.md +++ b/docs/blog/vitest-4.md @@ -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. 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 import { expect, test } from 'vitest' @@ -175,7 +175,7 @@ await expect.element(page.getByText('To')).toBeInViewport({ ratio: 0.5 }) ## 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). ![Playwright Traces interface](/traces.png) @@ -184,7 +184,7 @@ The traces are available in reporters as [annotations](/guide/test-annotations). ## Locator Improvements 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 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. -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 @@ -318,14 +318,14 @@ export default defineConfig({ ## 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. -- [`watcher`](/advanced/api/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. -- [`getSeed`](/advanced/api/vitest#enablecoverage) returns the seed value, if tests run at random. -- [`getGlobalTestNamePattern`](/advanced/api/vitest#getglobaltestnamepattern) returns the current test name pattern. -- [`waitForTestRunEnd`](/advanced/api/vitest#waitfortestrunend) returns a promise that resolves when all tests have finished running. +- [`experimental_parseSpecifications`](/api/advanced/vitest#parsespecification) allows you to parse a test file without running it. +- [`watcher`](/api/advanced/vitest#watcher) exposes methods that can be used when you disable the default Vitest watcher. +- [`enableCoverage`](/api/advanced/vitest#enablecoverage) and [`disableCoverage`](/api/advanced/vitest#disablecoverage) allow you to enable and disable coverage dynamically. +- [`getSeed`](/api/advanced/vitest#enablecoverage) returns the seed value, if tests run at random. +- [`getGlobalTestNamePattern`](/api/advanced/vitest#getglobaltestnamepattern) returns the current test name pattern. +- [`waitForTestRunEnd`](/api/advanced/vitest#waitfortestrunend) returns a promise that resolves when all tests have finished running. ## Breaking changes diff --git a/docs/config/alias.md b/docs/config/alias.md new file mode 100644 index 000000000..97ff2fa69 --- /dev/null +++ b/docs/config/alias.md @@ -0,0 +1,18 @@ +--- +title: alias | Config +outline: deep +--- + +# alias + +- **Type:** `Record | 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. +::: diff --git a/docs/config/allowonly.md b/docs/config/allowonly.md new file mode 100644 index 000000000..e6071032f --- /dev/null +++ b/docs/config/allowonly.md @@ -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. diff --git a/docs/config/api.md b/docs/config/api.md new file mode 100644 index 000000000..2bb16ecf5 --- /dev/null +++ b/docs/config/api.md @@ -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`. diff --git a/docs/config/attachmentsdir.md b/docs/config/attachmentsdir.md new file mode 100644 index 000000000..993fa9f83 --- /dev/null +++ b/docs/config/attachmentsdir.md @@ -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. diff --git a/docs/config/bail.md b/docs/config/bail.md new file mode 100644 index 000000000..27018e562 --- /dev/null +++ b/docs/config/bail.md @@ -0,0 +1,14 @@ +--- +title: bail | Config +outline: deep +--- + +# bail + +- **Type:** `number` +- **Default:** `0` +- **CLI**: `--bail=` + +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. diff --git a/docs/config/benchmark.md b/docs/config/benchmark.md new file mode 100644 index 000000000..ad9dea625 --- /dev/null +++ b/docs/config/benchmark.md @@ -0,0 +1,70 @@ +--- +title: benchmark | Config +outline: deep +--- + +# benchmark {#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` +- **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. diff --git a/docs/guide/browser/config.md b/docs/config/browser.md similarity index 95% rename from docs/guide/browser/config.md rename to docs/config/browser.md index f9e19b9be..5e3027bda 100644 --- a/docs/guide/browser/config.md +++ b/docs/config/browser.md @@ -1,3 +1,8 @@ +--- +title: Browser Config Reference | Config +outline: deep +--- + # 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: @@ -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. -You can specify most of the [project options](/config/) (not marked with a icon) and some of the `browser` options like `browser.testerHtmlPath`. +You can specify most of the [project options](/config/) (not marked with a icon) and some of the `browser` options like `browser.testerHtmlPath`. ::: warning Every browser config inherits options from the root config: @@ -89,7 +94,7 @@ List of available `browser` options: - [`browser.screenshotFailures`](#browser-screenshotfailures) - [`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 @@ -224,7 +229,7 @@ Default iframe's viewport. ## browser.locators -Options for built-in [browser locators](/guide/browser/locators). +Options for built-in [browser locators](/api/browser/locators). ### browser.locators.testIdAttribute @@ -292,7 +297,7 @@ export interface BrowserScript { - **Type:** `Record` - **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 @@ -346,7 +351,7 @@ interface TraceOptions { ``` ::: 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 @@ -367,7 +372,7 @@ Disabling this will completely remove all Vitest error handlers, which can help ### browser.expect.toMatchScreenshot 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. ::: 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 available: `resolveScreenshotPath` and `resolveDiffPath`. @@ -450,7 +455,7 @@ receives an object with the following properties: - `screenshotDirectory: string` The value provided to - [`browser.screenshotDirectory`](/guide/browser/config#browser-screenshotdirectory), + [`browser.screenshotDirectory`](/config/browser/screenshotdirectory), if none is provided, its default value. - `root: string` diff --git a/docs/config/browser/api.md b/docs/config/browser/api.md new file mode 100644 index 000000000..b1491e146 --- /dev/null +++ b/docs/config/browser/api.md @@ -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. diff --git a/docs/config/browser/commands.md b/docs/config/browser/commands.md new file mode 100644 index 000000000..b933f093a --- /dev/null +++ b/docs/config/browser/commands.md @@ -0,0 +1,11 @@ +--- +title: browser.commands | Config +outline: deep +--- + +# browser.commands + +- **Type:** `Record` +- **Default:** `{ readFile, writeFile, ... }` + +Custom [commands](/api/browser/commands) that can be imported during browser tests from `vitest/browser`. diff --git a/docs/config/browser/connecttimeout.md b/docs/config/browser/connecttimeout.md new file mode 100644 index 000000000..275b39b55 --- /dev/null +++ b/docs/config/browser/connecttimeout.md @@ -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. +::: diff --git a/docs/config/browser/enabled.md b/docs/config/browser/enabled.md new file mode 100644 index 000000000..766e85ba8 --- /dev/null +++ b/docs/config/browser/enabled.md @@ -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. diff --git a/docs/config/browser/expect.md b/docs/config/browser/expect.md new file mode 100644 index 000000000..501fb0c15 --- /dev/null +++ b/docs/config/browser/expect.md @@ -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` + +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 = ( + 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 +} +``` +::: diff --git a/docs/config/browser/headless.md b/docs/config/browser/headless.md new file mode 100644 index 000000000..f0bd1614b --- /dev/null +++ b/docs/config/browser/headless.md @@ -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. diff --git a/docs/config/browser/instances.md b/docs/config/browser/instances.md new file mode 100644 index 000000000..446545ea6 --- /dev/null +++ b/docs/config/browser/instances.md @@ -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 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. diff --git a/docs/config/browser/isolate.md b/docs/config/browser/isolate.md new file mode 100644 index 000000000..6663c85cb --- /dev/null +++ b/docs/config/browser/isolate.md @@ -0,0 +1,16 @@ +--- +title: browser.isolate | Config +outline: deep +--- + +# browser.isolate + +- **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. +::: diff --git a/docs/config/browser/locators.md b/docs/config/browser/locators.md new file mode 100644 index 000000000..c0e4991c0 --- /dev/null +++ b/docs/config/browser/locators.md @@ -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. diff --git a/docs/config/browser/orchestratorscripts.md b/docs/config/browser/orchestratorscripts.md new file mode 100644 index 000000000..7a4304296 --- /dev/null +++ b/docs/config/browser/orchestratorscripts.md @@ -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 +} +``` diff --git a/docs/guide/browser/playwright.md b/docs/config/browser/playwright.md similarity index 92% rename from docs/guide/browser/playwright.md rename to docs/config/browser/playwright.md index a3c0eda82..1e7fb0dee 100644 --- a/docs/guide/browser/playwright.md +++ b/docs/config/browser/playwright.md @@ -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). ::: 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. ::: @@ -86,14 +86,14 @@ Note that the context is created for every _test file_, not every _test_ like in ::: 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). -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` - **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: diff --git a/docs/guide/browser/preview.md b/docs/config/browser/preview.md similarity index 80% rename from docs/guide/browser/preview.md rename to docs/config/browser/preview.md index 8b8bb3d46..b563c084d 100644 --- a/docs/guide/browser/preview.md +++ b/docs/config/browser/preview.md @@ -1,7 +1,7 @@ # Configuring Preview ::: 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: @@ -24,9 +24,9 @@ This will open a new browser window using your default browser to run the tests. ## 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 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 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. diff --git a/docs/config/browser/provider.md b/docs/config/browser/provider.md new file mode 100644 index 000000000..2ef8d1410 --- /dev/null +++ b/docs/config/browser/provider.md @@ -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-` 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 advanced + +::: 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 + openPage: (sessionId: string, url: string) => Promise + getCDPSession?: (sessionId: string) => Promise + close: () => Awaitable +} +``` diff --git a/docs/config/browser/screenshotdirectory.md b/docs/config/browser/screenshotdirectory.md new file mode 100644 index 000000000..8cc87068a --- /dev/null +++ b/docs/config/browser/screenshotdirectory.md @@ -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`. diff --git a/docs/config/browser/screenshotfailures.md b/docs/config/browser/screenshotfailures.md new file mode 100644 index 000000000..4c787c5cb --- /dev/null +++ b/docs/config/browser/screenshotfailures.md @@ -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. diff --git a/docs/config/browser/testerhtmlpath.md b/docs/config/browser/testerhtmlpath.md new file mode 100644 index 000000000..7042e204d --- /dev/null +++ b/docs/config/browser/testerhtmlpath.md @@ -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. diff --git a/docs/config/browser/trace.md b/docs/config/browser/trace.md new file mode 100644 index 000000000..51b62eba5 --- /dev/null +++ b/docs/config/browser/trace.md @@ -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. +::: diff --git a/docs/config/browser/trackunhandlederrors.md b/docs/config/browser/trackunhandlederrors.md new file mode 100644 index 000000000..cab9a2d4e --- /dev/null +++ b/docs/config/browser/trackunhandlederrors.md @@ -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. diff --git a/docs/config/browser/ui.md b/docs/config/browser/ui.md new file mode 100644 index 000000000..4b437c963 --- /dev/null +++ b/docs/config/browser/ui.md @@ -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. diff --git a/docs/config/browser/viewport.md b/docs/config/browser/viewport.md new file mode 100644 index 000000000..e226a4536 --- /dev/null +++ b/docs/config/browser/viewport.md @@ -0,0 +1,11 @@ +--- +title: browser.viewport | Config +outline: deep +--- + +# browser.viewport + +- **Type:** `{ width, height }` +- **Default:** `414x896` + +Default iframe's viewport. diff --git a/docs/guide/browser/webdriverio.md b/docs/config/browser/webdriverio.md similarity index 91% rename from docs/guide/browser/webdriverio.md rename to docs/config/browser/webdriverio.md index bc07b09e7..988a8cdec 100644 --- a/docs/guide/browser/webdriverio.md +++ b/docs/config/browser/webdriverio.md @@ -1,7 +1,7 @@ # Configuring 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: @@ -60,5 +60,5 @@ You can find most available options in the [WebdriverIO documentation](https://w ::: 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. -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. ::: diff --git a/docs/config/cache.md b/docs/config/cache.md new file mode 100644 index 000000000..a480f6284 --- /dev/null +++ b/docs/config/cache.md @@ -0,0 +1,31 @@ +--- +title: cache | Config +outline: deep +--- + +# cache + +- **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 +}) +``` diff --git a/docs/config/chaiconfig.md b/docs/config/chaiconfig.md new file mode 100644 index 000000000..24cf085af --- /dev/null +++ b/docs/config/chaiconfig.md @@ -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. diff --git a/docs/config/clearmocks.md b/docs/config/clearmocks.md new file mode 100644 index 000000000..fff1dbfd0 --- /dev/null +++ b/docs/config/clearmocks.md @@ -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, + }, +}) +``` diff --git a/docs/config/coverage.md b/docs/config/coverage.md new file mode 100644 index 000000000..d760620c7 --- /dev/null +++ b/docs/config/coverage.md @@ -0,0 +1,397 @@ +--- +title: coverage | Config +outline: deep +--- + +# coverage {#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=` + +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=`, `--coverage.include= --coverage.include=` + +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=`, `--coverage.exclude= --coverage.exclude=` + +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=` + +::: 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=`, `--coverage.reporter= --coverage.reporter=` + +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: + + ```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. + + +```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. + + +```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=` + +Global threshold for lines. + +### coverage.thresholds.functions + +- **Type:** `number` +- **Available for providers:** `'v8' | 'istanbul'` +- **CLI:** `--coverage.thresholds.functions=` + +Global threshold for functions. + +### coverage.thresholds.branches + +- **Type:** `number` +- **Available for providers:** `'v8' | 'istanbul'` +- **CLI:** `--coverage.thresholds.branches=` + +Global threshold for branches. + +### coverage.thresholds.statements + +- **Type:** `number` +- **Available for providers:** `'v8' | 'istanbul'` +- **CLI:** `--coverage.thresholds.statements=` + +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=` + +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: + + +```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. +::: + + +```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. + + +```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=` + +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:** + +```ts +{ + statements?: [number, number], + functions?: [number, number], + branches?: [number, number], + lines?: [number, number] +} +``` + +- **Default:** + +```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=` + +Concurrency limit used when processing the coverage results. + +## coverage.customProviderModule + +- **Type:** `string` +- **Available for providers:** `'custom'` +- **CLI:** `--coverage.customProviderModule=` + +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. diff --git a/docs/config/css.md b/docs/config/css.md new file mode 100644 index 000000000..eb096d164 --- /dev/null +++ b/docs/config/css.md @@ -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. +::: diff --git a/docs/config/dangerouslyignoreunhandlederrors.md b/docs/config/dangerouslyignoreunhandlederrors.md new file mode 100644 index 000000000..54536f199 --- /dev/null +++ b/docs/config/dangerouslyignoreunhandlederrors.md @@ -0,0 +1,28 @@ +--- +title: dangerouslyIgnoreUnhandledErrors | Config +outline: deep +--- + +# dangerouslyIgnoreUnhandledErrors + +- **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, + }, +}) +``` diff --git a/docs/config/deps.md b/docs/config/deps.md new file mode 100644 index 000000000..b49b8fdde --- /dev/null +++ b/docs/config/deps.md @@ -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')], + } + }, +}) +``` diff --git a/docs/config/diff.md b/docs/config/diff.md new file mode 100644 index 000000000..ec8789175 --- /dev/null +++ b/docs/config/diff.md @@ -0,0 +1,99 @@ +--- +title: diff | Config +outline: deep +--- + +# diff + +- **Type:** `string` +- **CLI:** `--diff=` + +`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=` + +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 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 diff --git a/docs/config/dir.md b/docs/config/dir.md new file mode 100644 index 000000000..4fa15aead --- /dev/null +++ b/docs/config/dir.md @@ -0,0 +1,12 @@ +--- +title: dir | Config +outline: deep +--- + +# dir + +- **Type:** `string` +- **CLI:** `--dir=` +- **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 diff --git a/docs/config/disableconsoleintercept.md b/docs/config/disableconsoleintercept.md new file mode 100644 index 000000000..40c04f5f2 --- /dev/null +++ b/docs/config/disableconsoleintercept.md @@ -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. +::: diff --git a/docs/config/env.md b/docs/config/env.md new file mode 100644 index 000000000..eaf3ee134 --- /dev/null +++ b/docs/config/env.md @@ -0,0 +1,10 @@ +--- +title: env | Config +outline: deep +--- + +# env + +- **Type:** `Partial` + +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). diff --git a/docs/config/environment.md b/docs/config/environment.md new file mode 100644 index 000000000..d359278be --- /dev/null +++ b/docs/config/environment.md @@ -0,0 +1,100 @@ +--- +title: environment | Config +--- + +# environment + +- **Type:** `'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string` +- **Default:** `'node'` +- **CLI:** `--environment=` + +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 { + 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"] + } +} +``` +::: diff --git a/docs/config/environmentoptions.md b/docs/config/environmentoptions.md new file mode 100644 index 000000000..0a8e478cc --- /dev/null +++ b/docs/config/environmentoptions.md @@ -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. +::: diff --git a/docs/config/exclude.md b/docs/config/exclude.md new file mode 100644 index 000000000..7116ce6bf --- /dev/null +++ b/docs/config/exclude.md @@ -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/**', + ], + }, +}) +``` +::: diff --git a/docs/config/execargv.md b/docs/config/execargv.md new file mode 100644 index 000000000..78991e445 --- /dev/null +++ b/docs/config/execargv.md @@ -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. +::: diff --git a/docs/config/expandsnapshotdiff.md b/docs/config/expandsnapshotdiff.md new file mode 100644 index 000000000..47dc59b20 --- /dev/null +++ b/docs/config/expandsnapshotdiff.md @@ -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. diff --git a/docs/config/expect.md b/docs/config/expect.md new file mode 100644 index 000000000..1090f1710 --- /dev/null +++ b/docs/config/expect.md @@ -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 diff --git a/docs/config/faketimers.md b/docs/config/faketimers.md new file mode 100644 index 000000000..a389b4510 --- /dev/null +++ b/docs/config/faketimers.md @@ -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. diff --git a/docs/config/fileparallelism.md b/docs/config/fileparallelism.md new file mode 100644 index 000000000..20f1143fb --- /dev/null +++ b/docs/config/fileparallelism.md @@ -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). +::: diff --git a/docs/config/forcereruntriggers.md b/docs/config/forcereruntriggers.md new file mode 100644 index 000000000..342143e18 --- /dev/null +++ b/docs/config/forcereruntriggers.md @@ -0,0 +1,24 @@ +--- +title: forceRerunTriggers | Config +outline: deep +--- + +# forceRerunTriggers + +- **Type**: `string[]` +- **Default:** `['**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**']` + +Glob pattern of file paths that will trigger the whole suite rerun. When paired with the `--changed` argument will run the whole test suite if the trigger is found in the git diff. + +Useful if you are testing calling CLI commands, because Vite cannot construct a module graph: + +```ts +test('execute a script', async () => { + // Vitest cannot rerun this test, if content of `dist/index.js` changes + await execa('node', ['dist/index.js']) +}) +``` + +::: tip +Make sure that your files are not excluded by [`server.watch.ignored`](https://vitejs.dev/config/server-options.html#server-watch). +::: diff --git a/docs/config/globals.md b/docs/config/globals.md new file mode 100644 index 000000000..1dcf7ef0b --- /dev/null +++ b/docs/config/globals.md @@ -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"] + } +} +``` diff --git a/docs/config/globalsetup.md b/docs/config/globalsetup.md new file mode 100644 index 000000000..743704569 --- /dev/null +++ b/docs/config/globalsetup.md @@ -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 3.0.0] +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 2.0.0] +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() + }) +} +``` diff --git a/docs/config/hideskippedtests.md b/docs/config/hideskippedtests.md new file mode 100644 index 000000000..9f63b0c56 --- /dev/null +++ b/docs/config/hideskippedtests.md @@ -0,0 +1,12 @@ +--- +title: hideSkippedTests | Config +outline: deep +--- + +# hideSkippedTests + +- **Type:** `boolean` +- **CLI:** `--hideSkippedTests`, `--hide-skipped-tests` +- **Default:** `false` + +Hide logs for skipped tests diff --git a/docs/config/hooktimeout.md b/docs/config/hooktimeout.md new file mode 100644 index 000000000..b922a6350 --- /dev/null +++ b/docs/config/hooktimeout.md @@ -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. diff --git a/docs/config/include-source.md b/docs/config/include-source.md new file mode 100644 index 000000000..e1ee0ce80 --- /dev/null +++ b/docs/config/include-source.md @@ -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"] + } +} +``` +::: diff --git a/docs/config/include.md b/docs/config/include.md new file mode 100644 index 000000000..41373db95 --- /dev/null +++ b/docs/config/include.md @@ -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?', + ], + }, +}) +``` +::: diff --git a/docs/config/includetasklocation.md b/docs/config/includetasklocation.md new file mode 100644 index 000000000..312c6bb11 --- /dev/null +++ b/docs/config/includetasklocation.md @@ -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. +::: diff --git a/docs/config/index.md b/docs/config/index.md index ec30801cd..2922ea3f8 100644 --- a/docs/config/index.md +++ b/docs/config/index.md @@ -12,12 +12,10 @@ If you are using Vite and have a `vite.config` file, Vitest will read it to matc To configure `vitest` itself, add `test` property in your Vite config. You'll also need to add a reference to Vitest types using a [triple slash command](https://www.typescriptlang.org/docs/handbook/triple-slash-directives.html#-reference-types-) at the top of your config file, if you are importing `defineConfig` from `vite` itself. -::: details Open Config Examples -Using `defineConfig` from `vite` you should follow this: +If you are not using `vite`, add `defineConfig` imported from `vitest/config` to your config file: -```ts [vite.config.js] -/// -import { defineConfig } from 'vite' +```js [vitest.config.js] +import { defineConfig } from 'vitest/config' export default defineConfig({ test: { @@ -26,9 +24,9 @@ export default defineConfig({ }) ``` -The `` will stop working in Vitest 4, but you can already start migrating to `vitest/config`: +If you have a `vite` config already, you can add `/// ` to include the `test` types: -```ts [vite.config.js] +```js [vite.config.js] /// import { defineConfig } from 'vite' @@ -39,21 +37,9 @@ export default defineConfig({ }) ``` -Using `defineConfig` from `vitest/config` you should follow this: - -```ts [vitest.config.js] -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - // ... Specify options here. - }, -}) -``` - You can retrieve Vitest's default options to expand them if needed: -```ts [vitest.config.js] +```js [vitest.config.js] import { configDefaults, defineConfig } from 'vitest/config' export default defineConfig({ @@ -65,7 +51,7 @@ export default defineConfig({ When using a separate `vitest.config.js`, you can also extend Vite's options from another config file if needed: -```ts [vitest.config.js] +```js [vitest.config.js] import { defineConfig, mergeConfig } from 'vitest/config' import viteConfig from './vite.config' @@ -78,7 +64,7 @@ export default mergeConfig(viteConfig, defineConfig({ If your Vite config is defined as a function, you can define the config like this: -```ts [vitest.config.js] +```js [vitest.config.js] import { defineConfig, mergeConfig } from 'vitest/config' import viteConfig from './vite.config' @@ -91,2169 +77,7 @@ export default defineConfig(configEnv => mergeConfig( }) )) ``` -::: - -::: warning -_All listed options_ on this page are located within a `test` property inside the configuration: - -```ts [vitest.config.js] -export default defineConfig({ - test: { - exclude: [], - }, -}) -``` Since Vitest uses Vite config, you can also use any configuration option from [Vite](https://vitejs.dev/config/). For example, `define` to define global variables, or `resolve.alias` to define aliases - these options should be defined on the top level, _not_ within a `test` property. -Configuration options that are not supported inside a [project](/guide/projects) config have sign next to them. This means they can only be set in the root Vitest config. -::: - -### include - -- **Type:** `string[]` -- **Default:** `['**/*.{test,spec}.?(c|m)[jt]s?(x)']` -- **CLI:** `vitest [...include]`, `vitest **/*.test.js` - -A list of glob patterns that match your test files. - -::: tip NOTE -When using coverage, Vitest automatically adds test files `include` patterns to coverage's default `exclude` patterns. See [`coverage.exclude`](#coverage-exclude). -::: - -### exclude - -- **Type:** `string[]` -- **Default:** `['**/node_modules/**', '**/.git/**']` -- **CLI:** `vitest --exclude "**/excluded-file" --exclude "*/other-files/*.js"` - -A list of glob patterns that should be excluded from your test files. - -::: warning -This option does not affect coverage. If you need to remove certain files from the coverage report, use [`coverage.exclude`](#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`. -::: - -### includeSource - -- **Type:** `string[]` -- **Default:** `[]` - -Include globs for in-source test files. - -When defined, Vitest will run all matched files with `import.meta.vitest` inside. - -### name - -- **Type:** `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`](/advanced/api/test-project#name). - -Color used by CLI and UI can be changed by providing an object with `color` property. - -### server {#server} - -- **Type:** `{ sourcemap?, deps?, ... }` - -Module runner options. - -#### server.sourcemap - -- **Type:** `'inline' | boolean` -- **Default:** `'inline'` - -Inject inline source map to modules. - -#### server.debug - -- **Type:** `{ dump?, load? }` - -Module runner debugger options. - -#### server.debug.dump - -- **Type:** `boolean | string` - -Dump the transformed module to filesystem. Passing a string will dump to the specified path. - -#### server.debug.load - -- **Type:** `boolean` - -Read dumped module from filesystem whenever exists. Useful for debugging by modifying the dump result from the filesystem. - -#### server.deps - -- **Type:** `{ external?, inline?, ... }` - -Handling for dependencies resolution. - -#### server.deps.external - -- **Type:** `(string | RegExp)[]` -- **Default:** `[/\/node_modules\//]` - -Externalize means that Vite will bypass the package to the native Node. Externalized dependencies will not be applied to Vite's transformers and resolvers, so they do not support HMR on reload. By default, all packages inside `node_modules` are externalized. - -These options support package names as they are written in `node_modules` or specified inside [`deps.moduleDirectories`](#deps-moduledirectories). For example, package `@company/some-name` located inside `packages/some-name` should be specified as `some-name`, and `packages` should be included in `deps.moduleDirectories`. Basically, Vitest always checks the file path, not the actual package name. - -If regexp is used, Vitest calls it on the _file path_, not the package name. - -#### server.deps.inline - -- **Type:** `(string | RegExp)[] | true` -- **Default:** `[]` - -Vite will process inlined modules. This could be helpful to handle packages that ship `.js` in ESM format (that Node can't handle). - -If `true`, every dependency will be inlined. All dependencies, specified in [`ssr.noExternal`](https://vitejs.dev/guide/ssr.html#ssr-externals) will be inlined by default. - -#### server.deps.fallbackCJS - -- **Type** `boolean` -- **Default:** `false` - -When a dependency is a valid ESM package, try to guess the CJS version based on the path. This might be helpful, if a dependency has the wrong ESM file. - -This might potentially cause some misalignment if a package has different logic in ESM and CJS mode. - -#### server.deps.cacheDir - -- **Type** `string` -- **Default**: `'node_modules/.vite'` - -Directory to save cache files. - -### 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')], - } - }, -}) -``` - -### runner - -- **Type**: `VitestRunnerConstructor` -- **Default**: `node`, when running tests, or `benchmark`, when running benchmarks - -Path to a custom test runner. This is an advanced feature and should be used with custom library runners. You can read more about it in [the documentation](/advanced/runner). - -### 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` -- **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. - -### alias - -- **Type:** `Record | 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. -::: - -### globals - -- **Type:** `boolean` -- **Default:** `false` -- **CLI:** `--globals`, `--globals=false` - -By default, `vitest` does not provide global APIs for explicitness. If you prefer to use the APIs globally like Jest, you can pass the `--globals` option to CLI or add `globals: true` in the config. - -```ts -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - globals: true, - }, -}) -``` - -To get TypeScript working with the global APIs, add `vitest/globals` to the `types` field in your `tsconfig.json` - -```json [tsconfig.json] -{ - "compilerOptions": { - "types": ["vitest/globals"] - } -} -``` - -If you have redefined your [`typeRoots`](https://www.typescriptlang.org/tsconfig/#typeRoots) to include more types in your compilation, you will have 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"] - } -} -``` - -If you are already using [`unplugin-auto-import`](https://github.com/antfu/unplugin-auto-import) in your project, you can also use it directly for auto importing those APIs. - -```ts [vitest.config.js] -import { defineConfig } from 'vitest/config' -import AutoImport from 'unplugin-auto-import/vite' - -export default defineConfig({ - plugins: [ - AutoImport({ - imports: ['vitest'], - dts: true, // generate TypeScript declaration - }), - ], -}) -``` - -### environment - -- **Type:** `'node' | 'jsdom' | 'happy-dom' | 'edge-runtime' | string` -- **Default:** `'node'` -- **CLI:** `--environment=` - -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. -::: - -By adding a `@vitest-environment` docblock or comment at the top of the file, -you can specify another environment to be used for all tests in that file: - -Docblock style: - -```js -/** - * @vitest-environment jsdom - */ - -test('use jsdom in this test file', () => { - const element = document.createElement('div') - expect(element).not.toBeNull() -}) -``` - -Comment style: - -```js -// @vitest-environment happy-dom - -test('use happy-dom in this test file', () => { - const element = document.createElement('div') - expect(element).not.toBeNull() -}) -``` - -For compatibility with Jest, there is also a `@jest-environment`: - -```js -/** - * @jest-environment jsdom - */ - -test('use jsdom in this test file', () => { - const element = document.createElement('div') - expect(element).not.toBeNull() -}) -``` - -If you are running Vitest with [`--isolate=false`](#isolate) flag, your tests will be run in this order: `node`, `jsdom`, `happy-dom`, `edge-runtime`, `custom environments`. Meaning, that every test with the same environment is grouped, but is still running sequentially. - -Starting from 0.23.0, you can also define custom environment. When non-builtin environment is used, Vitest will try to load package `vitest-environment-${name}`. That package should export an object with the shape of `Environment`: - -```ts [environment.js] -import type { Environment } from 'vitest' - -export default { - name: 'custom', - viteEnvironment: 'ssr', - setup() { - // custom setup - return { - teardown() { - // called after all tests with this env have been run - } - } - } -} -``` - -Vitest also exposes `builtinEnvironments` through `vitest/environments` entry, in case you just want to extend it. You can read more about extending environments in [our guide](/guide/environment). - -::: 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"] - } -} -``` -::: - -### environmentOptions - -- **Type:** `Record<'jsdom' | string, unknown>` -- **Default:** `{}` - -These options are passed down to `setup` method of current [`environment`](#environment). By default, you can configure only JSDOM options, if you are using it as your test environment. - -### update - -- **Type:** `boolean` -- **Default:** `false` -- **CLI:** `-u`, `--update`, `--update=false` - -Update snapshot files. This will update all changed snapshots and delete obsolete ones. - -### watch - -- **Type:** `boolean` -- **Default:** `!process.env.CI && process.stdin.isTTY` -- **CLI:** `-w`, `--watch`, `--watch=false` - -Enable watch mode - -In interactive environments, this is the default, unless `--run` is specified explicitly. - -In CI, or when run from a non-interactive shell, "watch" mode is not the default, but can be enabled explicitly with this flag. - -### watchTriggerPatterns 3.2.0 {#watchtriggerpatterns} - -- **Type:** `WatcherTriggerPattern[]` - -Vitest reruns tests based on the module graph which is populated by static and dynamic `import` statements. However, if you are reading from the file system or fetching from a proxy, then Vitest cannot detect those dependencies. - -To correctly rerun those tests, you can define a regex pattern and a function that returns a list of test files to run. - -```ts -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - watchTriggerPatterns: [ - { - pattern: /^src\/(mailers|templates)\/(.*)\.(ts|html|txt)$/, - testsToRun: (id, match) => { - // relative to the root value - return `./api/tests/mailers/${match[2]}.test.ts` - }, - }, - ], - }, -}) -``` - -::: warning -Returned files should be either absolute or relative to the root. Note that this is a global option, and it cannot be used inside of [project](/guide/projects) configs. -::: - -### root - -- **Type:** `string` -- **CLI:** `-r `, `--root=` - -Project root - -### dir - -- **Type:** `string` -- **CLI:** `--dir=` -- **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 - -### reporters - -- **Type:** `Reporter | Reporter[]` -- **Default:** `'default'` -- **CLI:** `--reporter=`, `--reporter= --reporter=` - -Custom [reporters](/guide/reporters) for output. Reporters can be [a Reporter instance](https://github.com/vitest-dev/vitest/blob/main/packages/vitest/src/node/types/reporter.ts), a string to select built-in reporters, or a path to a custom implementation (e.g. `'./path/to/reporter.ts'`, `'@scope/reporter'`). - -### outputFile - -- **Type:** `string | Record` -- **CLI:** `--outputFile=`, `--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. - -### 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`. - -### execArgv - -- **Type:** `string[]` -- **Default:** `[]` -- **CLI:** `--execArgv= --execArgv=` - -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. - -```sh -vitest --execArgv=--cpu-prof --execArgv=--cpu-prof-dir=./cpu-profile -``` - -:::warning -Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103. -::: - -### vmMemoryLimit - -- **Type:** `string | number` -- **Default:** `1 / CPU Cores` - -This option affects only `vmForks` and `vmThreads` pools. - -Specifies the memory limit for workers before they are recycled. This value heavily depends on your environment, so it's better to specify it manually instead of relying on the default. - -::: tip -The implementation is based on Jest's [`workerIdleMemoryLimit`](https://jestjs.io/docs/configuration#workeridlememorylimit-numberstring). - -The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: - -- `<= 1` - The value is assumed to be a percentage of system memory. So 0.5 sets the memory limit of the worker to half of the total system memory -- `\> 1` - Assumed to be a fixed byte value. Because of the previous rule if you wanted a value of 1 byte (I don't know why) you could use 1.1. -- With units - - `50%` - As above, a percentage of total system memory - - `100KB`, `65MB`, etc - With units to denote a fixed memory limit. - - `K` / `KB` - Kilobytes (x1000) - - `KiB` - Kibibytes (x1024) - - `M` / `MB` - Megabytes - - `MiB` - Mebibytes - - `G` / `GB` - Gigabytes - - `GiB` - Gibibytes -::: - -::: warning -Percentage based memory limit [does not work on Linux CircleCI](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) workers due to incorrect system memory being reported. -::: - -### 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). -::: - -### maxWorkers - -- **Type:** `number | string` - -Maximum number or percentage of workers to run tests in. - -### testTimeout - -- **Type:** `number` -- **Default:** `5_000` in Node.js, `15_000` if `browser.enabled` is `true` -- **CLI:** `--test-timeout=5000`, `--testTimeout=5000` - -Default timeout of a test in milliseconds. Use `0` to disable timeout completely. - -### 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. - -### teardownTimeout - -- **Type:** `number` -- **Default:** `10000` -- **CLI:** `--teardown-timeout=5000`, `--teardownTimeout=5000` - -Default timeout to wait for close when Vitest shuts down, in milliseconds - -### silent - -- **Type:** `boolean | 'passed-only'` -- **Default:** `false` -- **CLI:** `--silent`, `--silent=false` - -Silent console output from tests. - -Use `'passed-only'` to see logs from failing tests only. Logs from failing tests are printed after a test has finished. - -### setupFiles - -- **Type:** `string | string[]` - -Path to setup files. They will be run before each test file. - -:::info -Editing a setup file will automatically trigger a rerun of all tests. -::: - -You can use `process.env.VITEST_POOL_ID` (integer-like string) inside to distinguish between threads. - -:::tip -Note, that if you are running [`--isolate=false`](#isolate), this setup file will be run in the same global scope multiple times. Meaning, that you are accessing the same global object before each test, so make sure you are not doing the same thing more than you need. -::: - -For example, you may rely on a global variable: - -```ts -import { config } from '@some-testing-lib' - -if (!globalThis.defined) { - config.plugins = [myCoolPlugin] - computeHeavyThing() - globalThis.defined = true -} - -// hooks are reset before each suite -afterEach(() => { - cleanup() -}) - -globalThis.resetBeforeEachTest = true -``` - -### provide 2.1.0 {#provide} - -- **Type:** `Partial` - -Define values that can be accessed inside your tests using `inject` method. - -:::code-group -```ts [vitest.config.js] -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - provide: { - API_KEY: '123', - }, - }, -}) -``` -```ts [api.test.js] -import { expect, inject, test } from 'vitest' - -test('api key is defined', () => { - expect(inject('API_KEY')).toBe('123') -}) -``` -::: - -::: warning -Properties have to be strings and values need to be [serializable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types) because this object will be transferred between different processes. -::: - -::: tip -If you are using TypeScript, you will need to augment `ProvidedContext` type for type safe access: - -```ts [vitest.shims.d.ts] -declare module 'vitest' { - export interface ProvidedContext { - API_KEY: string - } -} - -// mark this file as a module so augmentation works correctly -export {} -``` -::: - -### 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 3.0.0] -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 2.0.0] -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() - }) -} -``` - -### forceRerunTriggers - -- **Type**: `string[]` -- **Default:** `['**/package.json/**', '**/vitest.config.*/**', '**/vite.config.*/**']` - -Glob pattern of file paths that will trigger the whole suite rerun. When paired with the `--changed` argument will run the whole test suite if the trigger is found in the git diff. - -Useful if you are testing calling CLI commands, because Vite cannot construct a module graph: - -```ts -test('execute a script', async () => { - // Vitest cannot rerun this test, if content of `dist/index.js` changes - await execa('node', ['dist/index.js']) -}) -``` - -::: tip -Make sure that your files are not excluded by [`server.watch.ignored`](https://vitejs.dev/config/server-options.html#server-watch). -::: - -### 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=` - -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=`, `--coverage.include= --coverage.include=` - -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=`, `--coverage.exclude= --coverage.exclude=` - -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=` - -::: 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=`, `--coverage.reporter= --coverage.reporter=` - -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: - - ```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. - - -```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 2.1.0 {#coverage-exclude-after-remap} - -- **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. - - -```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=` - -Global threshold for lines. - -##### coverage.thresholds.functions - -- **Type:** `number` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.functions=` - -Global threshold for functions. - -##### coverage.thresholds.branches - -- **Type:** `number` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.branches=` - -Global threshold for branches. - -##### coverage.thresholds.statements - -- **Type:** `number` -- **Available for providers:** `'v8' | 'istanbul'` -- **CLI:** `--coverage.thresholds.statements=` - -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=` - -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: - - -```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. -::: - - -```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 2.1.0 {#coverage-thresholds-glob-pattern-100} - -- **Type:** `boolean` -- **Default:** `false` -- **Available for providers:** `'v8' | 'istanbul'` - -Sets thresholds to 100 for files matching the glob pattern. - - -```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=` - -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:** - -```ts -{ - statements?: [number, number], - functions?: [number, number], - branches?: [number, number], - lines?: [number, number] -} -``` - -- **Default:** - -```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=` - -Concurrency limit used when processing the coverage results. - -#### coverage.customProviderModule - -- **Type:** `string` -- **Available for providers:** `'custom'` -- **CLI:** `--coverage.customProviderModule=` - -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. - -### testNamePattern - -- **Type** `string | RegExp` -- **CLI:** `-t `, `--testNamePattern=`, `--test-name-pattern=` - -Run tests with full names matching the pattern. -If you add `OnlyRunThis` to this property, tests not containing the word `OnlyRunThis` in the test name will be skipped. - -```js -import { expect, test } from 'vitest' - -// run -test('OnlyRunThis', () => { - expect(true).toBe(true) -}) - -// skipped -test('doNotRun', () => { - expect(true).toBe(true) -}) -``` - -### open - -- **Type:** `boolean` -- **Default:** `!process.env.CI` -- **CLI:** `--open`, `--open=false` - -Open Vitest UI (WIP) - -### api - -- **Type:** `boolean | number` -- **Default:** `false` -- **CLI:** `--api`, `--api.port`, `--api.host`, `--api.strictPort` - -Listen to port and serve API. When set to true, the default port is 51204 - -### browser {#browser} - -- **Default:** `{ enabled: false }` -- **CLI:** `--browser=`, `--browser.name=chrome --browser.headless` - -Configuration for running browser tests. Please, refer to the ["Browser Config Reference"](/guide/browser/config) article. - -### clearMocks - -- **Type:** `boolean` -- **Default:** `false` - -Will call [`vi.clearAllMocks()`](/api/vi#vi-clearallmocks) before each test. -This will clear mock history without affecting mock implementations. - -### mockReset - -- **Type:** `boolean` -- **Default:** `false` - -Will call [`vi.resetAllMocks()`](/api/vi#vi-resetallmocks) before each test. -This will clear mock history and reset each implementation. - -### restoreMocks - -- **Type:** `boolean` -- **Default:** `false` - -Will call [`vi.restoreAllMocks()`](/api/vi#vi-restoreallmocks) before each test. - -This restores all original implementations on spies created with [`vi.spyOn`](#vi-spyon). - -### unstubEnvs {#unstubenvs} - -- **Type:** `boolean` -- **Default:** `false` - -Will call [`vi.unstubAllEnvs`](/api/vi#vi-unstuballenvs) before each test. - -### unstubGlobals {#unstubglobals} - -- **Type:** `boolean` -- **Default:** `false` - -Will call [`vi.unstubAllGlobals`](/api/vi#vi-unstuballglobals) before each test. - -### snapshotFormat - -- **Type:** `PrettyFormatOptions` - -Format options for snapshot testing. These options are passed down to our fork of [`pretty-format`](https://www.npmjs.com/package/pretty-format). In addition to the `pretty-format` options we support `printShadowRoot: boolean`. - -::: tip -Beware that `plugins` field on this object will be ignored. - -If you need to extend snapshot serializer via pretty-format plugins, please, use [`expect.addSnapshotSerializer`](/api/expect#expect-addsnapshotserializer) API or [snapshotSerializers](#snapshotserializers) option. -::: - -### snapshotSerializers {#snapshotserializers} - -- **Type:** `string[]` -- **Default:** `[]` - -A list of paths to snapshot serializer modules for snapshot testing, useful if you want add custom snapshot serializers. See [Custom Serializer](/guide/snapshot#custom-serializer) for more information. - -### resolveSnapshotPath - -- **Type**: `(testPath: string, snapExtension: string, context: { config: SerializedConfig }) => string` -- **Default**: stores snapshot files in `__snapshots__` directory - -Overrides default snapshot path. For example, to store snapshots next to test files: - -```ts -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - resolveSnapshotPath: (testPath, snapExtension) => testPath + snapExtension, - }, -}) -``` - -### allowOnly - -- **Type**: `boolean` -- **Default**: `!process.env.CI` -- **CLI:** `--allowOnly`, `--allowOnly=false` - -Allow tests and suites that are marked as only. - -### dangerouslyIgnoreUnhandledErrors - -- **Type**: `boolean` -- **Default**: `false` -- **CLI:** `--dangerouslyIgnoreUnhandledErrors` `--dangerouslyIgnoreUnhandledErrors=false` - -Ignore any unhandled errors that occur. - -### passWithNoTests - -- **Type**: `boolean` -- **Default**: `false` -- **CLI:** `--passWithNoTests`, `--passWithNoTests=false` - -Vitest will not fail, if no tests will be found. - -### logHeapUsage - -- **Type**: `boolean` -- **Default**: `false` -- **CLI:** `--logHeapUsage`, `--logHeapUsage=false` - -Show heap usage after each test. Useful for debugging memory leaks. - -### css - -- **Type**: `boolean | { include?, exclude?, modules? }` - -Configure if CSS should be processed. When excluded, CSS files will be replaced with empty strings to bypass the subsequent processing. CSS Modules will return a proxy to not affect runtime. - -#### css.include - -- **Type**: `RegExp | RegExp[]` -- **Default**: `[]` - -RegExp pattern for files that should return actual CSS and will be processed by Vite pipeline. - -:::tip -To process all CSS files, use `/.+/`. -::: - -#### 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. -::: - -### 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. - -### cache - -- **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 -}) -``` - -### sequence - -- **Type**: `{ sequencer?, shuffle?, seed?, hooks?, setupFiles?, groupOrder }` - -Options for how tests should be sorted. - -You can provide sequence options to CLI with dot notation: - -```sh -npx vitest --sequence.shuffle --sequence.seed=1000 -``` - -#### sequence.sequencer - -- **Type**: `TestSequencerConstructor` -- **Default**: `BaseSequencer` - -A custom class that defines methods for sharding and sorting. You can extend `BaseSequencer` from `vitest/node`, if you only need to redefine one of the `sort` and `shard` methods, but both should exist. - -Sharding is happening before sorting, and only if `--shard` option is provided. - -If [`sequencer.groupOrder`](#grouporder) is specified, the sequencer will be called once for each group and pool. - -#### groupOrder 3.2.0 {#grouporder} - -- **Type:** `number` -- **Default:** `0` - -Controls the order in which this project runs its tests when using multiple [projects](/guide/projects). - -- Projects with the same group order number will run together, and groups are run from lowest to highest. -- If you don’t set this option, all projects run in parallel. -- If several projects use the same group order, they will run at the same time. - -This setting only affects the order in which projects run, not the order of tests within a project. -To control test isolation or the order of tests inside a project, use the [`isolate`](#isolate) and [`sequence.sequencer`](#sequence-sequencer) options. - -::: details Example -Consider this example: - -```ts -import { defineConfig } from 'vitest/config' - -export default defineConfig({ - test: { - projects: [ - { - test: { - name: 'slow', - sequence: { - groupOrder: 0, - }, - }, - }, - { - test: { - name: 'fast', - sequence: { - groupOrder: 0, - }, - }, - }, - { - test: { - name: 'flaky', - sequence: { - groupOrder: 1, - }, - }, - }, - ], - }, -}) -``` - -Tests in these projects will run in this order: - -``` - 0. slow | - |> running together - 0. fast | - - 1. flaky |> runs after slow and fast alone -``` -::: - -#### sequence.shuffle - -- **Type**: `boolean | { files?, tests? }` -- **Default**: `false` -- **CLI**: `--sequence.shuffle`, `--sequence.shuffle=false` - -If you want files and tests to run randomly, you can enable it with this option, or CLI argument [`--sequence.shuffle`](/guide/cli). - -Vitest usually uses cache to sort tests, so long running tests start earlier - this makes tests run faster. If your files and tests will run in random order you will lose this performance improvement, but it may be useful to track tests that accidentally depend on another run previously. - -#### sequence.shuffle.files {#sequence-shuffle-files} - -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--sequence.shuffle.files`, `--sequence.shuffle.files=false` - -Whether to randomize files, be aware that long running tests will not start earlier if you enable this option. - -#### sequence.shuffle.tests {#sequence-shuffle-tests} - -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--sequence.shuffle.tests`, `--sequence.shuffle.tests=false` - -Whether to randomize tests. - -#### sequence.concurrent {#sequence-concurrent} - -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--sequence.concurrent`, `--sequence.concurrent=false` - -If you want tests to run in parallel, you can enable it with this option, or CLI argument [`--sequence.concurrent`](/guide/cli). - -::: 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). -::: - -#### sequence.seed - -- **Type**: `number` -- **Default**: `Date.now()` -- **CLI**: `--sequence.seed=1000` - -Sets the randomization seed, if tests are running in random order. - -#### sequence.hooks - -- **Type**: `'stack' | 'list' | 'parallel'` -- **Default**: `'stack'` -- **CLI**: `--sequence.hooks=` - -Changes the order in which hooks are executed. - -- `stack` will order "after" hooks in reverse order, "before" hooks will run in the order they were defined -- `list` will order all hooks in the order they are defined -- `parallel` will run hooks in a single group in parallel (hooks in parent suites will still run before the current suite's hooks) - -::: tip -This option doesn't affect [`onTestFinished`](/api/#ontestfinished). It is always called in reverse order. -::: - -#### sequence.setupFiles {#sequence-setupfiles} - -- **Type**: `'list' | 'parallel'` -- **Default**: `'parallel'` -- **CLI**: `--sequence.setupFiles=` - -Changes the order in which setup files are executed. - -- `list` will run setup files in the order they are defined -- `parallel` will run setup files in parallel - -### typecheck - -Options for configuring [typechecking](/guide/testing-types) test environment. - -#### typecheck.enabled {#typecheck-enabled} - -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--typecheck`, `--typecheck.enabled` - -Enable typechecking alongside your regular tests. - -#### typecheck.only {#typecheck-only} - -- **Type**: `boolean` -- **Default**: `false` -- **CLI**: `--typecheck.only` - -Run only typecheck tests, when typechecking is enabled. When using CLI, this option will automatically enable typechecking. - -#### typecheck.checker - -- **Type**: `'tsc' | 'vue-tsc' | string` -- **Default**: `tsc` - -What tools to use for type checking. Vitest will spawn a process with certain parameters for easier parsing, depending on the type. Checker should implement the same output format as `tsc`. - -You need to have a package installed to use typechecker: - -- `tsc` requires `typescript` package -- `vue-tsc` requires `vue-tsc` package - -You can also pass down a path to custom binary or command name that produces the same output as `tsc --noEmit --pretty false`. - -#### typecheck.include - -- **Type**: `string[]` -- **Default**: `['**/*.{test,spec}-d.?(c|m)[jt]s?(x)']` - -Glob pattern for files that should be treated as test files - -#### typecheck.exclude - -- **Type**: `string[]` -- **Default**: `['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**']` - -Glob pattern for files that should not be treated as test files - -#### typecheck.allowJs - -- **Type**: `boolean` -- **Default**: `false` - -Check JS files that have `@ts-check` comment. If you have it enabled in tsconfig, this will not overwrite it. - -#### typecheck.ignoreSourceErrors - -- **Type**: `boolean` -- **Default**: `false` - -Do not fail, if Vitest found errors outside the test files. This will not show you non-test errors at all. - -By default, if Vitest finds source error, it will fail test suite. - -#### typecheck.tsconfig - -- **Type**: `string` -- **Default**: _tries to find closest tsconfig.json_ - -Path to custom tsconfig, relative to the project root. - -#### typecheck.spawnTimeout - -- **Type**: `number` -- **Default**: `10_000` - -Minimum time in milliseconds it takes to spawn the typechecker. - -### slowTestThreshold - -- **Type**: `number` -- **Default**: `300` -- **CLI**: `--slow-test-threshold=`, `--slowTestThreshold=` - -The number of milliseconds after which a test or suite is considered slow and reported as such in the results. - -### chaiConfig {#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. - -### bail {#bail} - -- **Type:** `number` -- **Default:** `0` -- **CLI**: `--bail=` - -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. - -### retry {#retry} - -- **Type:** `number` -- **Default:** `0` -- **CLI:** `--retry=` - -Retry the test specific number of times if it fails. - -### onConsoleLog - -```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') - }, - }, -}) -``` - -### onStackTrace {#onstacktrace} - -- **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 - } - }, - }, -}) -``` - -### onUnhandledError {#onunhandlederror} - -- **Type:** `(error: (TestError | Error) & { type: string }) => boolean | void` - -A custom handler to filter out unhandled errors that should not be reported. If an error is filtered out, it will no longer affect the test results. - -If you want unhandled errors to be reported without impacting the test outcome, consider using the [`dangerouslyIgnoreUnhandledErrors`](#dangerouslyIgnoreUnhandledErrors) option - -```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 - } - }, - }, -}) -``` - -### diff - -- **Type:** `string` -- **CLI:** `--diff=` - -`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=` - -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 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 - -### 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. - -### projects {#projects} - -- **Type:** `TestProjectConfiguration[]` -- **Default:** `[]` - -An array of [projects](/guide/projects). - -### 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. -::: - -### includeTaskLocation {#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. -::: - -### snapshotEnvironment {#snapshotEnvironment} - -- **Type:** `string` - -Path to a custom snapshot environment implementation. This is useful if you are running your tests in an environment that doesn't support Node.js APIs. This option doesn't have any effect on a browser runner. - -This object should have the shape of `SnapshotEnvironment` and is used to resolve and read/write snapshot files: - -```ts -export interface SnapshotEnvironment { - getVersion: () => string - getHeader: () => string - resolvePath: (filepath: string) => Promise - resolveRawPath: (testPath: string, rawPath: string) => Promise - saveSnapshotFile: (filepath: string, snapshot: string) => Promise - readSnapshotFile: (filepath: string) => Promise - removeSnapshotFile: (filepath: string) => Promise -} -``` - -You can extend default `VitestSnapshotEnvironment` from `vitest/snapshot` entry point if you need to overwrite only a part of the API. - -::: warning -This is a low-level option and should be used only for advanced cases where you don't have access to default Node.js APIs. - -If you just need to configure snapshots feature, use [`snapshotFormat`](#snapshotformat) or [`resolveSnapshotPath`](#resolvesnapshotpath) options. -::: - -### env {#env} - -- **Type:** `Partial` - -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). - -### 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 - -### printConsoleTrace - -- **Type:** `boolean` -- **Default:** `false` - -Always print console traces when calling any `console` method. This is useful for debugging. - -### attachmentsDir 3.2.0 {#attachmentsdir} - -- **Type:** `string` -- **Default:** `'.vitest-attachments'` - -Directory path for storing attachments created by [`context.annotate`](/guide/test-context#annotate) relative to the project root. +Configuration options that are not supported inside a [project](/guide/projects) config have icon next to them. This means they can only be set in the root Vitest config. diff --git a/docs/config/isolate.md b/docs/config/isolate.md new file mode 100644 index 000000000..a92f055e3 --- /dev/null +++ b/docs/config/isolate.md @@ -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. +::: diff --git a/docs/config/logheapusage.md b/docs/config/logheapusage.md new file mode 100644 index 000000000..a29f251c9 --- /dev/null +++ b/docs/config/logheapusage.md @@ -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. diff --git a/docs/config/maxconcurrency.md b/docs/config/maxconcurrency.md new file mode 100644 index 000000000..6026efe77 --- /dev/null +++ b/docs/config/maxconcurrency.md @@ -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. diff --git a/docs/config/maxworkers.md b/docs/config/maxworkers.md new file mode 100644 index 000000000..4aa637784 --- /dev/null +++ b/docs/config/maxworkers.md @@ -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. diff --git a/docs/config/mockreset.md b/docs/config/mockreset.md new file mode 100644 index 000000000..fac9b6b7e --- /dev/null +++ b/docs/config/mockreset.md @@ -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, + }, +}) +``` diff --git a/docs/config/mode.md b/docs/config/mode.md new file mode 100644 index 000000000..5e45a97e2 --- /dev/null +++ b/docs/config/mode.md @@ -0,0 +1,12 @@ +--- +title: mode | Config +outline: deep +--- + +# mode + +- **Type:** `string` +- **CLI:** `--mode=staging` +- **Default:** `'test'` + +Overrides Vite mode diff --git a/docs/config/name.md b/docs/config/name.md new file mode 100644 index 000000000..26b8c6fac --- /dev/null +++ b/docs/config/name.md @@ -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. +::: diff --git a/docs/config/onconsolelog.md b/docs/config/onconsolelog.md new file mode 100644 index 000000000..bd4d34176 --- /dev/null +++ b/docs/config/onconsolelog.md @@ -0,0 +1,30 @@ +--- +title: onConsoleLog | Config +outline: deep +--- + +# onConsoleLog + +```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') + }, + }, +}) +``` diff --git a/docs/config/onstacktrace.md b/docs/config/onstacktrace.md new file mode 100644 index 000000000..920284a0d --- /dev/null +++ b/docs/config/onstacktrace.md @@ -0,0 +1,37 @@ +--- +title: onStackTrace | Config +outline: deep +--- + +# onStackTrace + +- **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 + } + }, + }, +}) +``` diff --git a/docs/config/onunhandlederror.md b/docs/config/onunhandlederror.md new file mode 100644 index 000000000..ec7b2dbee --- /dev/null +++ b/docs/config/onunhandlederror.md @@ -0,0 +1,40 @@ +--- +title: onUnhandledError | Config +outline: deep +--- + +# onUnhandledError 4.0.0 + +- **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 + } + }, + }, +}) +``` diff --git a/docs/config/open.md b/docs/config/open.md new file mode 100644 index 000000000..65c2c08f3 --- /dev/null +++ b/docs/config/open.md @@ -0,0 +1,12 @@ +--- +title: open | Config +outline: deep +--- + +# open + +- **Type:** `boolean` +- **Default:** `!process.env.CI` +- **CLI:** `--open`, `--open=false` + +Open Vitest UI automatically if it's [enabled](/config/ui). diff --git a/docs/config/outputfile.md b/docs/config/outputfile.md new file mode 100644 index 000000000..fc87b029a --- /dev/null +++ b/docs/config/outputfile.md @@ -0,0 +1,12 @@ +--- +title: outputFile | Config +outline: deep +--- + +# outputFile {#outputfile} + +- **Type:** `string | Record` +- **CLI:** `--outputFile=`, `--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. diff --git a/docs/config/passwithnotests.md b/docs/config/passwithnotests.md new file mode 100644 index 000000000..eb4bbe2ed --- /dev/null +++ b/docs/config/passwithnotests.md @@ -0,0 +1,12 @@ +--- +title: passWithNoTests | Config +outline: deep +--- + +# passWithNoTests + +- **Type**: `boolean` +- **Default**: `false` +- **CLI:** `--passWithNoTests`, `--passWithNoTests=false` + +Vitest will not fail, if no tests will be found. diff --git a/docs/config/pool.md b/docs/config/pool.md new file mode 100644 index 000000000..f9d1eac2c --- /dev/null +++ b/docs/config/pool.md @@ -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`. diff --git a/docs/config/printconsoletrace.md b/docs/config/printconsoletrace.md new file mode 100644 index 000000000..8552b6cd0 --- /dev/null +++ b/docs/config/printconsoletrace.md @@ -0,0 +1,11 @@ +--- +title: printConsoleTrace | Config +outline: deep +--- + +# printConsoleTrace + +- **Type:** `boolean` +- **Default:** `false` + +Always print console traces when calling any `console` method. This is useful for debugging. diff --git a/docs/config/projects.md b/docs/config/projects.md new file mode 100644 index 000000000..761861d12 --- /dev/null +++ b/docs/config/projects.md @@ -0,0 +1,11 @@ +--- +title: projects | Config +outline: deep +--- + +# projects + +- **Type:** `TestProjectConfiguration[]` +- **Default:** `[]` + +An array of [projects](/guide/projects). diff --git a/docs/config/provide.md b/docs/config/provide.md new file mode 100644 index 000000000..6eb1347b3 --- /dev/null +++ b/docs/config/provide.md @@ -0,0 +1,50 @@ +--- +title: provide | Config +outline: deep +--- + +# provide + +- **Type:** `Partial` + +Define values that can be accessed inside your tests using `inject` method. + +:::code-group +```ts [vitest.config.js] +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + provide: { + API_KEY: '123', + }, + }, +}) +``` +```ts [api.test.js] +import { expect, inject, test } from 'vitest' + +test('api key is defined', () => { + expect(inject('API_KEY')).toBe('123') +}) +``` +::: + +::: warning +Properties have to be strings and values need to be [serializable](https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm#supported_types) because this object will be transferred between different processes. +::: + +::: tip +If you are using TypeScript, you will need to augment `ProvidedContext` type for type safe access: + +```ts [vitest.shims.d.ts] +declare module 'vitest' { + export interface ProvidedContext { + API_KEY: string + } +} + +// mark this file as a module so augmentation works correctly +export {} +``` +::: diff --git a/docs/config/reporters.md b/docs/config/reporters.md new file mode 100644 index 000000000..d79ae59cd --- /dev/null +++ b/docs/config/reporters.md @@ -0,0 +1,72 @@ +--- +title: reporters | Config +--- + +# reporters + +- **Type:** + +```ts +interface UserConfig { + reporters?: ConfigReporter | Array +} + +type ConfigReporter = string | Reporter | [string, object?] +``` + +- **Default:** [`'default'`](/guide/reporters#default-reporter) +- **CLI:** + - `--reporter=tap` for a single reporter + - `--reporter=verbose --reporter=github-actions` for multiple reporters + +This option defines a single reporter or a list of reporters available to Vitest during the test run. + +Alongside built-in reporters, you can also pass down a custom implementation of a [`Reporter` interface](/api/advanced/reporters), or a path to a module that exports it as a default export (e.g. `'./path/to/reporter.ts'`, `'@scope/reporter'`). + +You can configure a reporter by providing a tuple: `[string, object]`, where the string is a reporter name, and the object is the reporter's options. + +::: warning +Note that the [coverage](/guide/coverage) feature uses a different [`coverage.reporter`](/config/coverage#reporter) option instead of this one. +::: + +## Built-in Reporters + +- [`default`](/guide/reporters#default-reporter) +- [`verbose`](/guide/reporters#verbose-reporter) +- [`tree`](/guide/reporters#tree-reporter) +- [`dot`](/guide/reporters#dot-reporter) +- [`junit`](/guide/reporters#junit-reporter) +- [`json`](/guide/reporters#json-reporter) +- [`html`](/guide/reporters#html-reporter) +- [`tap`](/guide/reporters#tap-reporter) +- [`tap-flat`](/guide/reporters#tap-flat-reporter) +- [`hanging-process`](/guide/reporters#hanging-process-reporter) +- [`github-actions`](/guide/reporters#github-actions-reporter) +- [`blob`](/guide/reporters#blob-reporter) + +## Example + +::: code-group +```js [vitest.config.js] +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + reporters: [ + 'default', + // conditional reporter + process.env.CI ? 'github-actions' : {}, + // custom reporter from npm package + // options are passed down as a tuple + [ + 'vitest-sonar-reporter', + { outputFile: 'sonar-report.xml' } + ], + ] + } +}) +``` +```bash [CLI] +vitest --reporter=github-actions --reporter=junit +``` +::: diff --git a/docs/config/resolvesnapshotpath.md b/docs/config/resolvesnapshotpath.md new file mode 100644 index 000000000..981ff4126 --- /dev/null +++ b/docs/config/resolvesnapshotpath.md @@ -0,0 +1,21 @@ +--- +title: resolveSnapshotPath | Config +outline: deep +--- + +# resolveSnapshotPath + +- **Type**: `(testPath: string, snapExtension: string, context: { config: SerializedConfig }) => string` +- **Default**: stores snapshot files in `__snapshots__` directory + +Overrides default snapshot path. For example, to store snapshots next to test files: + +```ts +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + resolveSnapshotPath: (testPath, snapExtension) => testPath + snapExtension, + }, +}) +``` diff --git a/docs/config/restoremocks.md b/docs/config/restoremocks.md new file mode 100644 index 000000000..006380088 --- /dev/null +++ b/docs/config/restoremocks.md @@ -0,0 +1,23 @@ +--- +title: restoreMocks | Config +outline: deep +--- + +# restoreMocks + +- **Type:** `boolean` +- **Default:** `false` + +Should Vitest automatically call [`vi.restoreAllMocks()`](/api/vi#vi-restoreallmocks) before each test. + +This restores all original implementations on spies created manually with [`vi.spyOn`](/api/vi#vi-spyon). + +```js [vitest.config.js] +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + restoreMocks: true, + }, +}) +``` diff --git a/docs/config/retry.md b/docs/config/retry.md new file mode 100644 index 000000000..48c0e8f10 --- /dev/null +++ b/docs/config/retry.md @@ -0,0 +1,12 @@ +--- +title: retry | Config +outline: deep +--- + +# retry + +- **Type:** `number` +- **Default:** `0` +- **CLI:** `--retry=` + +Retry the test specific number of times if it fails. diff --git a/docs/config/root.md b/docs/config/root.md new file mode 100644 index 000000000..3b4a429c6 --- /dev/null +++ b/docs/config/root.md @@ -0,0 +1,11 @@ +--- +title: root | Config +outline: deep +--- + +# root + +- **Type:** `string` +- **CLI:** `-r `, `--root=` + +Project root diff --git a/docs/config/runner.md b/docs/config/runner.md new file mode 100644 index 000000000..aaf20871c --- /dev/null +++ b/docs/config/runner.md @@ -0,0 +1,11 @@ +--- +title: runner | Config +outline: deep +--- + +# runner + +- **Type**: `VitestRunnerConstructor` +- **Default**: `node`, when running tests, or `benchmark`, when running benchmarks + +Path to a custom test runner. This is an advanced feature and should be used with custom library runners. You can read more about it in [the documentation](/api/advanced/runner). diff --git a/docs/config/sequence.md b/docs/config/sequence.md new file mode 100644 index 000000000..491a24f6e --- /dev/null +++ b/docs/config/sequence.md @@ -0,0 +1,163 @@ +--- +title: sequence | Config +outline: deep +--- + +# sequence + +- **Type**: `{ sequencer?, shuffle?, seed?, hooks?, setupFiles?, groupOrder }` + +Options for how tests should be sorted. + +You can provide sequence options to CLI with dot notation: + +```sh +npx vitest --sequence.shuffle --sequence.seed=1000 +``` + +## sequence.sequencer + +- **Type**: `TestSequencerConstructor` +- **Default**: `BaseSequencer` + +A custom class that defines methods for sharding and sorting. You can extend `BaseSequencer` from `vitest/node`, if you only need to redefine one of the `sort` and `shard` methods, but both should exist. + +Sharding is happening before sorting, and only if `--shard` option is provided. + +If [`sequencer.groupOrder`](#grouporder) is specified, the sequencer will be called once for each group and pool. + +## groupOrder + +- **Type:** `number` +- **Default:** `0` + +Controls the order in which this project runs its tests when using multiple [projects](/guide/projects). + +- Projects with the same group order number will run together, and groups are run from lowest to highest. +- If you don't set this option, all projects run in parallel. +- If several projects use the same group order, they will run at the same time. + +This setting only affects the order in which projects run, not the order of tests within a project. +To control test isolation or the order of tests inside a project, use the [`isolate`](#isolate) and [`sequence.sequencer`](#sequence-sequencer) options. + +::: details Example +Consider this example: + +```ts +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + projects: [ + { + test: { + name: 'slow', + sequence: { + groupOrder: 0, + }, + }, + }, + { + test: { + name: 'fast', + sequence: { + groupOrder: 0, + }, + }, + }, + { + test: { + name: 'flaky', + sequence: { + groupOrder: 1, + }, + }, + }, + ], + }, +}) +``` + +Tests in these projects will run in this order: + +``` + 0. slow | + |> running together + 0. fast | + + 1. flaky |> runs after slow and fast alone +``` +::: + +## sequence.shuffle + +- **Type**: `boolean | { files?, tests? }` +- **Default**: `false` +- **CLI**: `--sequence.shuffle`, `--sequence.shuffle=false` + +If you want files and tests to run randomly, you can enable it with this option, or CLI argument [`--sequence.shuffle`](/guide/cli). + +Vitest usually uses cache to sort tests, so long running tests start earlier - this makes tests run faster. If your files and tests will run in random order you will lose this performance improvement, but it may be useful to track tests that accidentally depend on another run previously. + +### sequence.shuffle.files {#sequence-shuffle-files} + +- **Type**: `boolean` +- **Default**: `false` +- **CLI**: `--sequence.shuffle.files`, `--sequence.shuffle.files=false` + +Whether to randomize files, be aware that long running tests will not start earlier if you enable this option. + +### sequence.shuffle.tests {#sequence-shuffle-tests} + +- **Type**: `boolean` +- **Default**: `false` +- **CLI**: `--sequence.shuffle.tests`, `--sequence.shuffle.tests=false` + +Whether to randomize tests. + +## sequence.concurrent {#sequence-concurrent} + +- **Type**: `boolean` +- **Default**: `false` +- **CLI**: `--sequence.concurrent`, `--sequence.concurrent=false` + +If you want tests to run in parallel, you can enable it with this option, or CLI argument [`--sequence.concurrent`](/guide/cli). + +::: 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). +::: + +## sequence.seed + +- **Type**: `number` +- **Default**: `Date.now()` +- **CLI**: `--sequence.seed=1000` + +Sets the randomization seed, if tests are running in random order. + +## sequence.hooks + +- **Type**: `'stack' | 'list' | 'parallel'` +- **Default**: `'stack'` +- **CLI**: `--sequence.hooks=` + +Changes the order in which hooks are executed. + +- `stack` will order "after" hooks in reverse order, "before" hooks will run in the order they were defined +- `list` will order all hooks in the order they are defined +- `parallel` will run hooks in a single group in parallel (hooks in parent suites will still run before the current suite's hooks) + +::: tip +This option doesn't affect [`onTestFinished`](/api/#ontestfinished). It is always called in reverse order. +::: + +## sequence.setupFiles {#sequence-setupfiles} + +- **Type**: `'list' | 'parallel'` +- **Default**: `'parallel'` +- **CLI**: `--sequence.setupFiles=` + +Changes the order in which setup files are executed. + +- `list` will run setup files in the order they are defined +- `parallel` will run setup files in parallel diff --git a/docs/config/server.md b/docs/config/server.md new file mode 100644 index 000000000..40ad74e98 --- /dev/null +++ b/docs/config/server.md @@ -0,0 +1,95 @@ +--- +title: server | Config +outline: deep +--- + +# server + +Before Vitest 4, this option was used to define the configuration for the `vite-node` server. + +At the moment, this option allows you to configure the inlining and externalization mechanisms, along with the module runner debugging configuration. + +::: warning +These options should be used only as the last resort to improve performance by externalizing auto-inlined dependencies or to fix issues by inlining invalid external dependencies. + +Normally, Vitest should do this automatically. +::: + +## deps + +### external + +- **Type:** `(string | RegExp)[]` +- **Default:** files inside [`moduleDirectories`](/config/deps#moduledirectories) + +Specifies modules that should not be transformed by Vite and should instead be processed directly by the engine. These modules are imported via native dynamic `import` and bypass both transformation and resolution phases. + +```js [vitest.config.js] +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + server: { + deps: { + external: ['react'], + }, + }, + }, +}) +``` + +External modules and their dependencies are not present in the module graph and will not trigger test restarts when they change. + +Typically, packages under `node_modules` are externalized. + +::: tip +If a string is provided, it is first normalized by prefixing the `/node_modules/` or other [`moduleDirectories`](/config/deps#moduledirectories) segments (for example, `'react'` becomes `/node_modules/react/`), and the resulting string is then matched against the full file path. For example, package `@company/some-name` located inside `packages/some-name` should be specified as `some-name`, and `packages` should be included in `deps.moduleDirectories`. + +If a `RegExp` is provided, it is matched against the full file path. +::: + +### inline + +- **Type:** `(string | RegExp)[] | true` +- **Default:** everything that is not externalized + +Specifies modules that should be transformed and resolved by Vite. These modules are run by Vite's [module runner](https://vite.dev/guide/api-environment-runtimes#modulerunner). + +Typically, your source files are inlined. + +::: tip +If a string is provided, it is first normalized by prefixing the `/node_modules/` or other [`moduleDirectories`](/config/deps#moduledirectories) segments (for example, `'react'` becomes `/node_modules/react/`), and the resulting string is then matched against the full file path. For example, package `@company/some-name` located inside `packages/some-name` should be specified as `some-name`, and `packages` should be included in `deps.moduleDirectories`. + +If a `RegExp` is provided, it is matched against the full file path. +::: + +### fallbackCJS + +- **Type:** `boolean` +- **Default:** `false` + +When a dependency is a valid ESM package, try to guess the cjs version based on the path. This might be helpful, if a dependency has the wrong ESM file. + +This might potentially cause some misalignment if a package has different logic in ESM and CJS mode. + +## debug + +### dump + +- **Type:** `string | boolean` +- **Default:** `false` + +The folder where Vitest stores the contents of inlined test files that can be inspected manually. + +If set to `true`, Vitest dumps the files inside the `.vitest-dump` folder relative to the root of the project. + +You can also use `VITEST_DEBUG_DUMP` env variable to enable this conditionally. + +### load + +- **Type:** `boolean` +- **Default:** `false` + +Read files from the dump instead of transforming them. If dump is disabled, this does nothing. + +You can also use `VITEST_DEBUG_LOAD_DUMP` env variable to enable this conditionally. diff --git a/docs/config/setupfiles.md b/docs/config/setupfiles.md new file mode 100644 index 000000000..f07fc0ea5 --- /dev/null +++ b/docs/config/setupfiles.md @@ -0,0 +1,39 @@ +--- +title: setupFiles | Config +outline: deep +--- + +# setupFiles + +- **Type:** `string | string[]` + +Path to setup files. They will be run before each test file. + +:::info +Editing a setup file will automatically trigger a rerun of all tests. +::: + +You can use `process.env.VITEST_POOL_ID` (integer-like string) inside to distinguish between workers. + +:::tip +Note, that if you are running [`--isolate=false`](#isolate), this setup file will be run in the same global scope multiple times. Meaning, that you are accessing the same global object before each test, so make sure you are not doing the same thing more than you need. +::: + +For example, you may rely on a global variable: + +```ts +import { config } from '@some-testing-lib' + +if (!globalThis.defined) { + config.plugins = [myCoolPlugin] + computeHeavyThing() + globalThis.defined = true +} + +// hooks are reset before each suite +afterEach(() => { + cleanup() +}) + +globalThis.resetBeforeEachTest = true +``` diff --git a/docs/config/silent.md b/docs/config/silent.md new file mode 100644 index 000000000..d7f11fff9 --- /dev/null +++ b/docs/config/silent.md @@ -0,0 +1,14 @@ +--- +title: silent | Config +outline: deep +--- + +# silent {#silent} + +- **Type:** `boolean | 'passed-only'` +- **Default:** `false` +- **CLI:** `--silent`, `--silent=false` + +Silent console output from tests. + +Use `'passed-only'` to see logs from failing tests only. Logs from failing tests are printed after a test has finished. diff --git a/docs/config/slowtestthreshold.md b/docs/config/slowtestthreshold.md new file mode 100644 index 000000000..84f9594d2 --- /dev/null +++ b/docs/config/slowtestthreshold.md @@ -0,0 +1,12 @@ +--- +title: slowTestThreshold | Config +outline: deep +--- + +# slowTestThreshold + +- **Type**: `number` +- **Default**: `300` +- **CLI**: `--slow-test-threshold=`, `--slowTestThreshold=` + +The number of milliseconds after which a test or suite is considered slow and reported as such in the results. diff --git a/docs/config/snapshotenvironment.md b/docs/config/snapshotenvironment.md new file mode 100644 index 000000000..889b56840 --- /dev/null +++ b/docs/config/snapshotenvironment.md @@ -0,0 +1,32 @@ +--- +title: snapshotEnvironment | Config +outline: deep +--- + +# snapshotEnvironment + +- **Type:** `string` + +Path to a custom snapshot environment implementation. This is useful if you are running your tests in an environment that doesn't support Node.js APIs. This option doesn't have any effect on a browser runner. + +This object should have the shape of `SnapshotEnvironment` and is used to resolve and read/write snapshot files: + +```ts +export interface SnapshotEnvironment { + getVersion: () => string + getHeader: () => string + resolvePath: (filepath: string) => Promise + resolveRawPath: (testPath: string, rawPath: string) => Promise + saveSnapshotFile: (filepath: string, snapshot: string) => Promise + readSnapshotFile: (filepath: string) => Promise + removeSnapshotFile: (filepath: string) => Promise +} +``` + +You can extend default `VitestSnapshotEnvironment` from `vitest/snapshot` entry point if you need to overwrite only a part of the API. + +::: warning +This is a low-level option and should be used only for advanced cases where you don't have access to default Node.js APIs. + +If you just need to configure snapshots feature, use [`snapshotFormat`](#snapshotformat) or [`resolveSnapshotPath`](#resolvesnapshotpath) options. +::: diff --git a/docs/config/snapshotformat.md b/docs/config/snapshotformat.md new file mode 100644 index 000000000..d0e00fc34 --- /dev/null +++ b/docs/config/snapshotformat.md @@ -0,0 +1,16 @@ +--- +title: snapshotFormat | Config +outline: deep +--- + +# snapshotFormat + +- **Type:** `PrettyFormatOptions` + +Format options for snapshot testing. These options are passed down to our fork of [`pretty-format`](https://www.npmjs.com/package/pretty-format). In addition to the `pretty-format` options we support `printShadowRoot: boolean`. + +::: tip +Beware that `plugins` field on this object will be ignored. + +If you need to extend snapshot serializer via pretty-format plugins, please, use [`expect.addSnapshotSerializer`](/api/expect#expect-addsnapshotserializer) API or [snapshotSerializers](#snapshotserializers) option. +::: diff --git a/docs/config/snapshotserializers.md b/docs/config/snapshotserializers.md new file mode 100644 index 000000000..0a1ae9a7c --- /dev/null +++ b/docs/config/snapshotserializers.md @@ -0,0 +1,11 @@ +--- +title: snapshotSerializers | Config +outline: deep +--- + +# snapshotSerializers + +- **Type:** `string[]` +- **Default:** `[]` + +A list of paths to snapshot serializer modules for snapshot testing, useful if you want add custom snapshot serializers. See [Custom Serializer](/guide/snapshot#custom-serializer) for more information. diff --git a/docs/config/teardowntimeout.md b/docs/config/teardowntimeout.md new file mode 100644 index 000000000..1fc9365aa --- /dev/null +++ b/docs/config/teardowntimeout.md @@ -0,0 +1,12 @@ +--- +title: teardownTimeout | Config +outline: deep +--- + +# teardownTimeout {#teardowntimeout} + +- **Type:** `number` +- **Default:** `10000` +- **CLI:** `--teardown-timeout=5000`, `--teardownTimeout=5000` + +Default timeout to wait for close when Vitest shuts down, in milliseconds diff --git a/docs/config/testnamepattern.md b/docs/config/testnamepattern.md new file mode 100644 index 000000000..7e4b4098a --- /dev/null +++ b/docs/config/testnamepattern.md @@ -0,0 +1,26 @@ +--- +title: testNamePattern | Config +outline: deep +--- + +# testNamePattern {#testnamepattern} + +- **Type** `string | RegExp` +- **CLI:** `-t `, `--testNamePattern=`, `--test-name-pattern=` + +Run tests with full names matching the pattern. +If you add `OnlyRunThis` to this property, tests not containing the word `OnlyRunThis` in the test name will be skipped. + +```js +import { expect, test } from 'vitest' + +// run +test('OnlyRunThis', () => { + expect(true).toBe(true) +}) + +// skipped +test('doNotRun', () => { + expect(true).toBe(true) +}) +``` diff --git a/docs/config/testtimeout.md b/docs/config/testtimeout.md new file mode 100644 index 000000000..9132d255c --- /dev/null +++ b/docs/config/testtimeout.md @@ -0,0 +1,12 @@ +--- +title: testTimeout | Config +outline: deep +--- + +# testTimeout + +- **Type:** `number` +- **Default:** `5_000` in Node.js, `15_000` if `browser.enabled` is `true` +- **CLI:** `--test-timeout=5000`, `--testTimeout=5000` + +Default timeout of a test in milliseconds. Use `0` to disable timeout completely. diff --git a/docs/config/typecheck.md b/docs/config/typecheck.md new file mode 100644 index 000000000..cae1854ab --- /dev/null +++ b/docs/config/typecheck.md @@ -0,0 +1,82 @@ +--- +title: typecheck | Config +outline: deep +--- + +# typecheck {#typecheck} + +Options for configuring [typechecking](/guide/testing-types) test environment. + +## typecheck.enabled {#typecheck-enabled} + +- **Type**: `boolean` +- **Default**: `false` +- **CLI**: `--typecheck`, `--typecheck.enabled` + +Enable typechecking alongside your regular tests. + +## typecheck.only {#typecheck-only} + +- **Type**: `boolean` +- **Default**: `false` +- **CLI**: `--typecheck.only` + +Run only typecheck tests, when typechecking is enabled. When using CLI, this option will automatically enable typechecking. + +## typecheck.checker + +- **Type**: `'tsc' | 'vue-tsc' | string` +- **Default**: `tsc` + +What tools to use for type checking. Vitest will spawn a process with certain parameters for easier parsing, depending on the type. Checker should implement the same output format as `tsc`. + +You need to have a package installed to use typechecker: + +- `tsc` requires `typescript` package +- `vue-tsc` requires `vue-tsc` package + +You can also pass down a path to custom binary or command name that produces the same output as `tsc --noEmit --pretty false`. + +## typecheck.include + +- **Type**: `string[]` +- **Default**: `['**/*.{test,spec}-d.?(c|m)[jt]s?(x)']` + +Glob pattern for files that should be treated as test files + +## typecheck.exclude + +- **Type**: `string[]` +- **Default**: `['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**']` + +Glob pattern for files that should not be treated as test files + +## typecheck.allowJs + +- **Type**: `boolean` +- **Default**: `false` + +Check JS files that have `@ts-check` comment. If you have it enabled in tsconfig, this will not overwrite it. + +## typecheck.ignoreSourceErrors + +- **Type**: `boolean` +- **Default**: `false` + +Do not fail, if Vitest found errors outside the test files. This will not show you non-test errors at all. + +By default, if Vitest finds source error, it will fail test suite. + +## typecheck.tsconfig + +- **Type**: `string` +- **Default**: _tries to find closest tsconfig.json_ + +Path to custom tsconfig, relative to the project root. + +## typecheck.spawnTimeout + +- **Type**: `number` +- **Default**: `10_000` + +Minimum time in milliseconds it takes to spawn the typechecker. diff --git a/docs/config/ui.md b/docs/config/ui.md new file mode 100644 index 000000000..e3bac62aa --- /dev/null +++ b/docs/config/ui.md @@ -0,0 +1,16 @@ +--- +title: ui | Config +outline: deep +--- + +# ui + +- **Type:** `boolean` +- **Default:** `false` +- **CLI:** `--ui`, `--ui=false` + +Enable [Vitest UI](/guide/ui). + +::: warning +This features requires a [`@vitest/ui`](https://www.npmjs.com/package/@vitest/ui) package to be installed. If you do not have it already, Vitest will install it when you run the test command for the first time. +::: diff --git a/docs/config/unstubenvs.md b/docs/config/unstubenvs.md new file mode 100644 index 000000000..9deaabda1 --- /dev/null +++ b/docs/config/unstubenvs.md @@ -0,0 +1,21 @@ +--- +title: unstubEnvs | Config +outline: deep +--- + +# unstubEnvs + +- **Type:** `boolean` +- **Default:** `false` + +Should Vitest automatically call [`vi.unstubAllEnvs()`](/api/vi#vi-unstuballenvs) before each test. + +```js [vitest.config.js] +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + unstubEnvs: true, + }, +}) +``` diff --git a/docs/config/unstubglobals.md b/docs/config/unstubglobals.md new file mode 100644 index 000000000..6c0d984bc --- /dev/null +++ b/docs/config/unstubglobals.md @@ -0,0 +1,21 @@ +--- +title: unstubGlobals | Config +outline: deep +--- + +# unstubGlobals + +- **Type:** `boolean` +- **Default:** `false` + +Should Vitest automatically call [`vi.unstubAllGlobals()`](/api/vi#vi-unstuballglobals) before each test. + +```js [vitest.config.js] +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + unstubGlobals: true, + }, +}) +``` diff --git a/docs/config/update.md b/docs/config/update.md new file mode 100644 index 000000000..8668b8e20 --- /dev/null +++ b/docs/config/update.md @@ -0,0 +1,12 @@ +--- +title: update | Config +outline: deep +--- + +# update {#update} + +- **Type:** `boolean` +- **Default:** `false` +- **CLI:** `-u`, `--update`, `--update=false` + +Update snapshot files. This will update all changed snapshots and delete obsolete ones. diff --git a/docs/config/vmmemorylimit.md b/docs/config/vmmemorylimit.md new file mode 100644 index 000000000..118d9bb1a --- /dev/null +++ b/docs/config/vmmemorylimit.md @@ -0,0 +1,35 @@ +--- +title: vmMemoryLimit | Config +outline: deep +--- + +# vmMemoryLimit + +- **Type:** `string | number` +- **Default:** `1 / CPU Cores` + +This option affects only `vmForks` and `vmThreads` pools. + +Specifies the memory limit for workers before they are recycled. This value heavily depends on your environment, so it's better to specify it manually instead of relying on the default. + +::: tip +The implementation is based on Jest's [`workerIdleMemoryLimit`](https://jestjs.io/docs/configuration#workeridlememorylimit-numberstring). + +The limit can be specified in a number of different ways and whatever the result is `Math.floor` is used to turn it into an integer value: + +- `<= 1` - The value is assumed to be a percentage of system memory. So 0.5 sets the memory limit of the worker to half of the total system memory +- `\> 1` - Assumed to be a fixed byte value. Because of the previous rule if you wanted a value of 1 byte (I don't know why) you could use 1.1. +- With units + - `50%` - As above, a percentage of total system memory + - `100KB`, `65MB`, etc - With units to denote a fixed memory limit. + - `K` / `KB` - Kilobytes (x1000) + - `KiB` - Kibibytes (x1024) + - `M` / `MB` - Megabytes + - `MiB` - Mebibytes + - `G` / `GB` - Gigabytes + - `GiB` - Gibibytes +::: + +::: warning +Percentage based memory limit [does not work on Linux CircleCI](https://github.com/jestjs/jest/issues/11956#issuecomment-1212925677) workers due to incorrect system memory being reported. +::: diff --git a/docs/config/watch.md b/docs/config/watch.md new file mode 100644 index 000000000..22fe6a5e9 --- /dev/null +++ b/docs/config/watch.md @@ -0,0 +1,16 @@ +--- +title: watch | Config +outline: deep +--- + +# watch {#watch} + +- **Type:** `boolean` +- **Default:** `!process.env.CI && process.stdin.isTTY` +- **CLI:** `-w`, `--watch`, `--watch=false` + +Enable watch mode + +In interactive environments, this is the default, unless `--run` is specified explicitly. + +In CI, or when run from a non-interactive shell, "watch" mode is not the default, but can be enabled explicitly with this flag. diff --git a/docs/config/watchtriggerpatterns.md b/docs/config/watchtriggerpatterns.md new file mode 100644 index 000000000..2041def75 --- /dev/null +++ b/docs/config/watchtriggerpatterns.md @@ -0,0 +1,34 @@ +--- +title: watchTriggerPatterns | Config +outline: deep +--- + +# watchTriggerPatterns 3.2.0 + +- **Type:** `WatcherTriggerPattern[]` + +Vitest reruns tests based on the module graph which is populated by static and dynamic `import` statements. However, if you are reading from the file system or fetching from a proxy, then Vitest cannot detect those dependencies. + +To correctly rerun those tests, you can define a regex pattern and a function that returns a list of test files to run. + +```ts +import { defineConfig } from 'vitest/config' + +export default defineConfig({ + test: { + watchTriggerPatterns: [ + { + pattern: /^src\/(mailers|templates)\/(.*)\.(ts|html|txt)$/, + testsToRun: (id, match) => { + // relative to the root value + return `./api/tests/mailers/${match[2]}.test.ts` + }, + }, + ], + }, +}) +``` + +::: warning +Returned files should be either absolute or relative to the root. Note that this is a global option, and it cannot be used inside of [project](/guide/projects) configs. +::: diff --git a/docs/advanced/api/index.md b/docs/guide/advanced/index.md similarity index 91% rename from docs/advanced/api/index.md rename to docs/guide/advanced/index.md index b1e8b1b14..01bca471a 100644 --- a/docs/advanced/api/index.md +++ b/docs/guide/advanced/index.md @@ -2,7 +2,7 @@ title: Advanced API --- -# Getting Started +# Getting Started advanced {#getting-started} ::: warning This guide lists advanced APIs to run tests via a Node.js script. If you just want to [run tests](/guide/), you probably don't need this. It is primarily used by library authors. @@ -32,7 +32,7 @@ const vitest = await startVitest('test') await vitest.close() ``` -`startVitest` function returns [`Vitest`](/advanced/api/vitest) instance if tests can be started. +`startVitest` function returns [`Vitest`](/api/advanced/vitest) instance if tests can be started. If watch mode is not enabled, Vitest will call `close` method automatically. @@ -42,7 +42,7 @@ You can pass down a list of filters as a second argument. Vitest will run only t Additionally, you can use the third argument to pass in CLI arguments, which will override any test config options. Alternatively, you can pass in the complete Vite config as the fourth argument, which will take precedence over any other user-defined options. -After running the tests, you can get the results from the [`state.getTestModules`](/advanced/api/test-module) API: +After running the tests, you can get the results from the [`state.getTestModules`](/api/advanced/test-module) API: ```ts import type { TestModule } from 'vitest/node' @@ -53,7 +53,7 @@ console.log(vitest.state.getTestModules()) // [TestModule] ``` ::: tip -The ["Running Tests"](/advanced/guide/tests#startvitest) guide has a usage example. +The ["Running Tests"](/guide/advanced/tests#startvitest) guide has a usage example. ::: ## createVitest @@ -67,7 +67,7 @@ function createVitest( ): Promise ``` -You can create Vitest instance by using `createVitest` function. It returns the same [`Vitest`](/advanced/api/vitest) instance as `startVitest`, but it doesn't start tests and doesn't validate installed packages. +You can create Vitest instance by using `createVitest` function. It returns the same [`Vitest`](/api/advanced/vitest) instance as `startVitest`, but it doesn't start tests and doesn't validate installed packages. ```js import { createVitest } from 'vitest/node' @@ -78,7 +78,7 @@ const vitest = await createVitest('test', { ``` ::: tip -The ["Running Tests"](/advanced/guide/tests#createvitest) guide has a usage example. +The ["Running Tests"](/guide/advanced/tests#createvitest) guide has a usage example. ::: ## resolveConfig diff --git a/docs/advanced/pool.md b/docs/guide/advanced/pool.md similarity index 98% rename from docs/advanced/pool.md rename to docs/guide/advanced/pool.md index 89fcdad70..ea632de7f 100644 --- a/docs/advanced/pool.md +++ b/docs/guide/advanced/pool.md @@ -1,4 +1,4 @@ -# Custom Pool +# Custom Pool advanced {#custom-pool} ::: warning This is an advanced, experimental and very low-level API. If you just want to [run tests](/guide/), you probably don't need this. It is primarily used by library authors. diff --git a/docs/advanced/reporters.md b/docs/guide/advanced/reporters.md similarity index 96% rename from docs/advanced/reporters.md rename to docs/guide/advanced/reporters.md index a426861d8..8fd9c4a1b 100644 --- a/docs/advanced/reporters.md +++ b/docs/guide/advanced/reporters.md @@ -1,4 +1,4 @@ -# Extending Reporters +# Extending Reporters advanced {#extending-reporters} ::: warning This is an advanced API. If you just want to configure built-in reporters, read the ["Reporters"](/guide/reporters) guide. diff --git a/docs/advanced/guide/tests.md b/docs/guide/advanced/tests.md similarity index 89% rename from docs/advanced/guide/tests.md rename to docs/guide/advanced/tests.md index 8bfc5060b..81d7b572d 100644 --- a/docs/advanced/guide/tests.md +++ b/docs/guide/advanced/tests.md @@ -1,4 +1,4 @@ -# Running Tests +# Running Tests advanced {#running-tests} ::: warning This guide explains how to use the advanced API to run tests via a Node.js script. If you just want to [run tests](/guide/), you probably don't need this. It is primarily used by library authors. @@ -28,12 +28,12 @@ for (const testModule of testModules) { ``` ::: tip -[`TestModule`](/advanced/api/test-module), [`TestSuite`](/advanced/api/test-suite) and [`TestCase`](/advanced/api/test-case) APIs are not experimental and follow SemVer since Vitest 2.1. +[`TestModule`](/api/advanced/test-module), [`TestSuite`](/api/advanced/test-suite) and [`TestCase`](/api/advanced/test-case) APIs are not experimental and follow SemVer since Vitest 2.1. ::: ## `createVitest` -Creates a [Vitest](/advanced/api/vitest) instances without running tests. +Creates a [Vitest](/api/advanced/vitest) instances without running tests. `createVitest` method doesn't validate that required packages are installed. It also doesn't respect `config.standalone` or `config.mergeReports`. Vitest won't be closed automatically even if `watch` is disabled. @@ -69,9 +69,9 @@ finally { } ``` -If you intend to keep the `Vitest` instance, make sure to at least call [`init`](/advanced/api/vitest#init). This will initialise reporters and the coverage provider, but won't run any tests. It is also recommended to enable the `watch` mode even if you don't intend to use the Vitest watcher, but want to keep the instance running. Vitest relies on this flag for some of its features to work correctly in a continuous process. +If you intend to keep the `Vitest` instance, make sure to at least call [`init`](/api/advanced/vitest#init). This will initialise reporters and the coverage provider, but won't run any tests. It is also recommended to enable the `watch` mode even if you don't intend to use the Vitest watcher, but want to keep the instance running. Vitest relies on this flag for some of its features to work correctly in a continuous process. -After reporters are initialised, use [`runTestSpecifications`](/advanced/api/vitest#runtestspecifications) or [`rerunTestSpecifications`](/advanced/api/vitest#reruntestspecifications) to run tests if manual run is required: +After reporters are initialised, use [`runTestSpecifications`](/api/advanced/vitest#runtestspecifications) or [`rerunTestSpecifications`](/api/advanced/vitest#reruntestspecifications) to run tests if manual run is required: ```ts watcher.on('change', async (file) => { diff --git a/docs/guide/browser/component-testing.md b/docs/guide/browser/component-testing.md index fe6e80f4d..59e591106 100644 --- a/docs/guide/browser/component-testing.md +++ b/docs/guide/browser/component-testing.md @@ -181,7 +181,7 @@ If your framework gets official Vitest support later, you can gradually migrate Ensure tests run in real browser environments for the most accurate testing. Browser Mode provides accurate CSS rendering, real browser APIs, and proper event handling. ### 2. Test User Interactions -Simulate real user behavior using Vitest's [Interactivity API](/guide/browser/interactivity-api). Use `page.getByRole()` and `userEvent` methods as shown in our [Advanced Testing Patterns](#advanced-testing-patterns): +Simulate real user behavior using Vitest's [Interactivity API](/api/browser/interactivity). Use `page.getByRole()` and `userEvent` methods as shown in our [Advanced Testing Patterns](#advanced-testing-patterns): ```tsx // Good: Test actual user interactions @@ -570,6 +570,6 @@ import { render } from 'vitest-browser-react' // [!code ++] ## Learn More - [Browser Mode Documentation](/guide/browser/) -- [Assertion API](/guide/browser/assertion-api) -- [Interactivity API](/guide/browser/interactivity-api) +- [Assertion API](/api/browser/assertions) +- [Interactivity API](/api/browser/interactivity) - [Example Repository](https://github.com/vitest-tests/browser-examples) diff --git a/docs/guide/browser/index.md b/docs/guide/browser/index.md index ee021e34e..49f364814 100644 --- a/docs/guide/browser/index.md +++ b/docs/guide/browser/index.md @@ -35,7 +35,7 @@ bunx vitest init browser ### Manual Installation -You can also install packages manually. Vitest always requires a provider to be defined. You can chose either [`preview`](/guide/browser/preview), [`playwright`](/guide/browser/playwright) or [`webdriverio`](/guide/browser/webdriverio). +You can also install packages manually. Vitest always requires a provider to be defined. You can chose either [`preview`](/config/browser/preview), [`playwright`](/config/browser/playwright) or [`webdriverio`](/config/browser/webdriverio). If you want to just preview how your tests look, you can use the `preview` provider: @@ -120,7 +120,7 @@ export default defineConfig({ ::: info Vitest assigns port `63315` to avoid conflicts with the development server, allowing you to run both in parallel. You can change that with the [`browser.api`](/config/#browser-api) option. -Since Vitest 2.1.5, the CLI no longer prints the Vite URL automatically. You can press "b" to print the URL when running in watch mode. +The CLI does not prints the Vite server URL automatically. You can press "b" to print the URL when running in watch mode. ::: If you have not used Vite before, make sure you have your framework's plugin installed and specified in the config. Some frameworks might require extra configuration to work - check their Vite related documentation to be sure. @@ -405,7 +405,7 @@ Community packages are available for other frameworks: If your framework is not represented, feel free to create your own package - it is a simple wrapper around the framework renderer and `page.elementLocator` API. We will add a link to it on this page. Make sure it has a name starting with `vitest-browser-`. -Besides rendering components and locating elements, you will also need to make assertions. Vitest forks the [`@testing-library/jest-dom`](https://github.com/testing-library/jest-dom) library to provide a wide range of DOM assertions out of the box. Read more at the [Assertions API](/guide/browser/assertion-api). +Besides rendering components and locating elements, you will also need to make assertions. Vitest forks the [`@testing-library/jest-dom`](https://github.com/testing-library/jest-dom) library to provide a wide range of DOM assertions out of the box. Read more at the [Assertions API](/api/browser/assertions). ```ts import { expect } from 'vitest' @@ -414,7 +414,7 @@ import { page } from 'vitest/browser' await expect.element(page.getByText('Hello World')).toBeInTheDocument() ``` -Vitest exposes a [Context API](/guide/browser/context) with a small set of utilities that might be useful to you in tests. For example, if you need to make an interaction, like clicking an element or typing text into an input, you can use `userEvent` from `vitest/browser`. Read more at the [Interactivity API](/guide/browser/interactivity-api). +Vitest exposes a [Context API](/api/browser/context) with a small set of utilities that might be useful to you in tests. For example, if you need to make an interaction, like clicking an element or typing text into an input, you can use `userEvent` from `vitest/browser`. Read more at the [Interactivity API](/api/browser/interactivity). ```ts import { page, userEvent } from 'vitest/browser' @@ -534,7 +534,7 @@ For unsupported frameworks, we recommend using `testing-library` packages: You can also see more examples in [`browser-examples`](https://github.com/vitest-tests/browser-examples) repository. ::: warning -`testing-library` provides a package `@testing-library/user-event`. We do not recommend using it directly because it simulates events instead of actually triggering them - instead, use [`userEvent`](/guide/browser/interactivity-api) imported from `vitest/browser` that uses Chrome DevTools Protocol or Webdriver (depending on the provider) under the hood. +`testing-library` provides a package `@testing-library/user-event`. We do not recommend using it directly because it simulates events instead of actually triggering them - instead, use [`userEvent`](/api/browser/interactivity) imported from `vitest/browser` that uses Chrome DevTools Protocol or Webdriver (depending on the provider) under the hood. ::: ::: code-group diff --git a/docs/guide/browser/multiple-setups.md b/docs/guide/browser/multiple-setups.md index d682539bb..ee9ca4be5 100644 --- a/docs/guide/browser/multiple-setups.md +++ b/docs/guide/browser/multiple-setups.md @@ -1,6 +1,6 @@ # Multiple Setups -You can specify several different browser setups using the [`browser.instances`](/guide/browser/config#browser-instances) option. +You can specify several different browser setups using the [`browser.instances`](/config/browser/instances) option. The main advantage of using the `browser.instances` over the [test projects](/guide/projects) is improved caching. Every project will use the same Vite server meaning the file transform and [dependency pre-bundling](https://vite.dev/guide/dep-pre-bundling.html) has to happen only once. diff --git a/docs/guide/browser/trace-view.md b/docs/guide/browser/trace-view.md index d78db55d9..52882d6b4 100644 --- a/docs/guide/browser/trace-view.md +++ b/docs/guide/browser/trace-view.md @@ -1,9 +1,9 @@ # Trace View -Vitest Browser Mode supports generating Playwright's [trace files](https://playwright.dev/docs/trace-viewer#viewing-remote-traces). To enable tracing, you need to set the [`trace`](/guide/browser/config#browser-trace) option in the `test.browser` configuration. +Vitest Browser Mode supports generating Playwright's [trace files](https://playwright.dev/docs/trace-viewer#viewing-remote-traces). To enable tracing, you need to set the [`trace`](/config/browser/trace) option in the `test.browser` configuration. ::: warning -Generating trace files is only available when using the [Playwright provider](/guide/browser/playwright). +Generating trace files is only available when using the [Playwright provider](/config/browser/playwright). ::: ::: code-group diff --git a/docs/guide/browser/visual-regression-testing.md b/docs/guide/browser/visual-regression-testing.md index 101253f8d..ea890aa70 100644 --- a/docs/guide/browser/visual-regression-testing.md +++ b/docs/guide/browser/visual-regression-testing.md @@ -50,7 +50,7 @@ or [Docker containers](https://playwright.dev/docs/docker). ::: 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 import { expect, test } from 'vitest' @@ -144,7 +144,7 @@ During stability detection, Vitest calls comparators with `createDiff: false` si ### Global Configuration Configure visual regression testing defaults in your -[Vitest config](/guide/browser/config#browser-expect-tomatchscreenshot): +[Vitest config](/config/browser/expect#tomatchscreenshot): ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' diff --git a/docs/guide/cli-generated.md b/docs/guide/cli-generated.md index 72e916abb..5d621a190 100644 --- a/docs/guide/cli-generated.md +++ b/docs/guide/cli-generated.md @@ -1,7 +1,7 @@ ### root - **CLI:** `-r, --root ` -- **Config:** [root](/config/#root) +- **Config:** [root](/config/root) Root path @@ -14,42 +14,41 @@ Path to config file ### update - **CLI:** `-u, --update` -- **Config:** [update](/config/#update) +- **Config:** [update](/config/update) Update snapshot ### watch - **CLI:** `-w, --watch` -- **Config:** [watch](/config/#watch) +- **Config:** [watch](/config/watch) Enable watch mode ### testNamePattern - **CLI:** `-t, --testNamePattern ` -- **Config:** [testNamePattern](/config/#testnamepattern) +- **Config:** [testNamePattern](/config/testnamepattern) Run tests with full names matching the specified regexp pattern ### dir - **CLI:** `--dir ` -- **Config:** [dir](/config/#dir) +- **Config:** [dir](/config/dir) Base directory to scan for the test files ### ui - **CLI:** `--ui` -- **Config:** [ui](/config/#ui) Enable UI ### open - **CLI:** `--open` -- **Config:** [open](/config/#open) +- **Config:** [open](/config/open) Open UI automatically (default: `!process.env.CI`) @@ -74,7 +73,7 @@ Set to true to exit if port is already in use, instead of automatically trying t ### silent - **CLI:** `--silent [value]` -- **Config:** [silent](/config/#silent) +- **Config:** [silent](/config/silent) Silent console output from tests. Use `'passed-only'` to see logs from failing tests only. @@ -87,112 +86,112 @@ Hide logs for skipped tests ### reporters - **CLI:** `--reporter ` -- **Config:** [reporters](/config/#reporters) +- **Config:** [reporters](/config/reporters) Specify reporters (default, blob, verbose, dot, json, tap, tap-flat, junit, tree, hanging-process, github-actions) ### outputFile - **CLI:** `--outputFile ` -- **Config:** [outputFile](/config/#outputfile) +- **Config:** [outputFile](/config/outputfile) Write test results to a file when supporter reporter is also specified, use cac's dot notation for individual outputs of multiple reporters (example: `--outputFile.tap=./tap.txt`) ### coverage.provider - **CLI:** `--coverage.provider ` -- **Config:** [coverage.provider](/config/#coverage-provider) +- **Config:** [coverage.provider](/config/coverage#coverage-provider) Select the tool for coverage collection, available values are: "v8", "istanbul" and "custom" ### coverage.enabled - **CLI:** `--coverage.enabled` -- **Config:** [coverage.enabled](/config/#coverage-enabled) +- **Config:** [coverage.enabled](/config/coverage#coverage-enabled) Enables coverage collection. Can be overridden using the `--coverage` CLI option (default: `false`) ### coverage.include - **CLI:** `--coverage.include ` -- **Config:** [coverage.include](/config/#coverage-include) +- **Config:** [coverage.include](/config/coverage#coverage-include) Files included in coverage as glob patterns. May be specified more than once when using multiple patterns. By default only files covered by tests are included. ### coverage.exclude - **CLI:** `--coverage.exclude ` -- **Config:** [coverage.exclude](/config/#coverage-exclude) +- **Config:** [coverage.exclude](/config/coverage#coverage-exclude) Files to be excluded in coverage. May be specified more than once when using multiple extensions. ### coverage.clean - **CLI:** `--coverage.clean` -- **Config:** [coverage.clean](/config/#coverage-clean) +- **Config:** [coverage.clean](/config/coverage#coverage-clean) Clean coverage results before running tests (default: true) ### coverage.cleanOnRerun - **CLI:** `--coverage.cleanOnRerun` -- **Config:** [coverage.cleanOnRerun](/config/#coverage-cleanonrerun) +- **Config:** [coverage.cleanOnRerun](/config/coverage#coverage-cleanonrerun) Clean coverage report on watch rerun (default: true) ### coverage.reportsDirectory - **CLI:** `--coverage.reportsDirectory ` -- **Config:** [coverage.reportsDirectory](/config/#coverage-reportsdirectory) +- **Config:** [coverage.reportsDirectory](/config/coverage#coverage-reportsdirectory) Directory to write coverage report to (default: ./coverage) ### coverage.reporter - **CLI:** `--coverage.reporter ` -- **Config:** [coverage.reporter](/config/#coverage-reporter) +- **Config:** [coverage.reporter](/config/coverage#coverage-reporter) -Coverage reporters to use. Visit [`coverage.reporter`](https://vitest.dev/config/#coverage-reporter) for more information (default: `["text", "html", "clover", "json"]`) +Coverage reporters to use. Visit [`coverage.reporter`](/config/#coverage-reporter) for more information (default: `["text", "html", "clover", "json"]`) ### coverage.reportOnFailure - **CLI:** `--coverage.reportOnFailure` -- **Config:** [coverage.reportOnFailure](/config/#coverage-reportonfailure) +- **Config:** [coverage.reportOnFailure](/config/coverage#coverage-reportonfailure) Generate coverage report even when tests fail (default: `false`) ### coverage.allowExternal - **CLI:** `--coverage.allowExternal` -- **Config:** [coverage.allowExternal](/config/#coverage-allowexternal) +- **Config:** [coverage.allowExternal](/config/coverage#coverage-allowexternal) Collect coverage of files outside the project root (default: `false`) ### coverage.skipFull - **CLI:** `--coverage.skipFull` -- **Config:** [coverage.skipFull](/config/#coverage-skipfull) +- **Config:** [coverage.skipFull](/config/coverage#coverage-skipfull) Do not show files with 100% statement, branch, and function coverage (default: `false`) ### coverage.thresholds.100 - **CLI:** `--coverage.thresholds.100` -- **Config:** [coverage.thresholds.100](/config/#coverage-thresholds-100) +- **Config:** [coverage.thresholds.100](/config/coverage#coverage-thresholds-100) Shortcut to set all coverage thresholds to 100 (default: `false`) ### coverage.thresholds.perFile - **CLI:** `--coverage.thresholds.perFile` -- **Config:** [coverage.thresholds.perFile](/config/#coverage-thresholds-perfile) +- **Config:** [coverage.thresholds.perFile](/config/coverage#coverage-thresholds-perfile) Check thresholds per file. See `--coverage.thresholds.lines`, `--coverage.thresholds.functions`, `--coverage.thresholds.branches` and `--coverage.thresholds.statements` for the actual thresholds (default: `false`) ### coverage.thresholds.autoUpdate - **CLI:** `--coverage.thresholds.autoUpdate ` -- **Config:** [coverage.thresholds.autoUpdate](/config/#coverage-thresholds-autoupdate) +- **Config:** [coverage.thresholds.autoUpdate](/config/coverage#coverage-thresholds-autoupdate) Update threshold values: "lines", "functions", "branches" and "statements" to configuration file when current coverage is above the configured thresholds (default: `false`) @@ -223,23 +222,23 @@ Threshold for statements. Visit [istanbuljs](https://github.com/istanbuljs/nyc#c ### coverage.ignoreClassMethods - **CLI:** `--coverage.ignoreClassMethods ` -- **Config:** [coverage.ignoreClassMethods](/config/#coverage-ignoreclassmethods) +- **Config:** [coverage.ignoreClassMethods](/config/coverage#coverage-ignoreclassmethods) Array of class method names to ignore for coverage. Visit [istanbuljs](https://github.com/istanbuljs/nyc#ignoring-methods) for more information. This option is only available for the istanbul providers (default: `[]`) ### coverage.processingConcurrency - **CLI:** `--coverage.processingConcurrency ` -- **Config:** [coverage.processingConcurrency](/config/#coverage-processingconcurrency) +- **Config:** [coverage.processingConcurrency](/config/coverage#coverage-processingconcurrency) Concurrency limit used when processing the coverage results. (default min between 20 and the number of CPUs) ### coverage.customProviderModule - **CLI:** `--coverage.customProviderModule ` -- **Config:** [coverage.customProviderModule](/config/#coverage-customprovidermodule) +- **Config:** [coverage.customProviderModule](/config/coverage#coverage-customprovidermodule) -Specifies the module name or path for the custom coverage provider module. Visit [Custom Coverage Provider](https://vitest.dev/guide/coverage#custom-coverage-provider) for more information. This option is only available for custom providers +Specifies the module name or path for the custom coverage provider module. Visit [Custom Coverage Provider](/guide/coverage#custom-coverage-provider) for more information. This option is only available for custom providers ### coverage.watermarks.statements @@ -268,21 +267,21 @@ High and low watermarks for functions in the format of `,` ### mode - **CLI:** `--mode ` -- **Config:** [mode](/config/#mode) +- **Config:** [mode](/config/mode) Override Vite mode (default: `test` or `benchmark`) ### isolate - **CLI:** `--isolate` -- **Config:** [isolate](/config/#isolate) +- **Config:** [isolate](/config/isolate) Run every test file in isolation. To disable isolation, use `--no-isolate` (default: `true`) ### globals - **CLI:** `--globals` -- **Config:** [globals](/config/#globals) +- **Config:** [globals](/config/globals) Inject apis globally @@ -295,483 +294,478 @@ Mock browser API with happy-dom ### browser.enabled - **CLI:** `--browser.enabled` -- **Config:** [browser.enabled](/guide/browser/config#browser-enabled) +- **Config:** [browser.enabled](/config/browser/enabled) Run tests in the browser. Equivalent to `--browser.enabled` (default: `false`) ### browser.name - **CLI:** `--browser.name ` -- **Config:** [browser.name](/guide/browser/config#browser-name) -Run all tests in a specific browser. Some browsers are only available for specific providers (see `--browser.provider`). Visit [`browser.name`](https://vitest.dev/guide/browser/config/#browser-name) for more information +Run all tests in a specific browser. Some browsers are only available for specific providers (see `--browser.provider`). ### browser.headless - **CLI:** `--browser.headless` -- **Config:** [browser.headless](/guide/browser/config#browser-headless) +- **Config:** [browser.headless](/config/browser/headless) Run the browser in headless mode (i.e. without opening the GUI (Graphical User Interface)). If you are running Vitest in CI, it will be enabled by default (default: `process.env.CI`) ### browser.api.port - **CLI:** `--browser.api.port [port]` -- **Config:** [browser.api.port](/guide/browser/config#browser-api-port) +- **Config:** [browser.api.port](/config/browser/api#api-port) Specify server port. Note if the port is already being used, Vite will automatically try the next available port so this may not be the actual port the server ends up listening on. If true will be set to `63315` ### browser.api.host - **CLI:** `--browser.api.host [host]` -- **Config:** [browser.api.host](/guide/browser/config#browser-api-host) +- **Config:** [browser.api.host](/config/browser/api#api-host) Specify which IP addresses the server should listen on. Set this to `0.0.0.0` or `true` to listen on all addresses, including LAN and public addresses ### browser.api.strictPort - **CLI:** `--browser.api.strictPort` -- **Config:** [browser.api.strictPort](/guide/browser/config#browser-api-strictport) +- **Config:** [browser.api.strictPort](/config/browser/api#api-strictport) Set to true to exit if port is already in use, instead of automatically trying the next available port ### browser.provider - **CLI:** `--browser.provider ` -- **Config:** [browser.provider](/guide/browser/config#browser-provider) +- **Config:** [browser.provider](/config/browser/provider) -Provider used to run browser tests. Some browsers are only available for specific providers. Can be "webdriverio", "playwright", "preview", or the path to a custom provider. Visit [`browser.provider`](https://vitest.dev/guide/browser/config.html#browser-provider) for more information (default: `"preview"`) +Provider used to run browser tests. Some browsers are only available for specific providers. Can be "webdriverio", "playwright", "preview", or the path to a custom provider. Visit [`browser.provider`](/config/browser/provider) for more information ### browser.isolate - **CLI:** `--browser.isolate` -- **Config:** [browser.isolate](/guide/browser/config#browser-isolate) +- **Config:** [browser.isolate](/config/browser/isolate) Run every browser test file in isolation. To disable isolation, use `--browser.isolate=false` (default: `true`) ### browser.ui - **CLI:** `--browser.ui` -- **Config:** [browser.ui](/guide/browser/config#browser-ui) +- **Config:** [browser.ui](/config/browser/ui) Show Vitest UI when running tests (default: `!process.env.CI`) ### browser.fileParallelism - **CLI:** `--browser.fileParallelism` -- **Config:** [browser.fileParallelism](/guide/browser/config#browser-fileparallelism) Should browser test files run in parallel. Use `--browser.fileParallelism=false` to disable (default: `true`) ### browser.connectTimeout - **CLI:** `--browser.connectTimeout ` -- **Config:** [browser.connectTimeout](/guide/browser/config#browser-connecttimeout) +- **Config:** [browser.connectTimeout](/config/browser/connecttimeout) If connection to the browser takes longer, the test suite will fail (default: `60_000`) ### browser.trackUnhandledErrors - **CLI:** `--browser.trackUnhandledErrors` -- **Config:** [browser.trackUnhandledErrors](/guide/browser/config#browser-trackunhandlederrors) +- **Config:** [browser.trackUnhandledErrors](/config/browser/trackunhandlederrors) Control if Vitest catches uncaught exceptions so they can be reported (default: `true`) ### browser.trace - **CLI:** `--browser.trace ` -- **Config:** [browser.trace](/guide/browser/config#browser-trace) +- **Config:** [browser.trace](/config/browser/trace) Enable trace view mode. Supported: "on", "off", "on-first-retry", "on-all-retries", "retain-on-failure". ### pool - **CLI:** `--pool ` -- **Config:** [pool](/config/#pool) +- **Config:** [pool](/config/pool) Specify pool, if not running in the browser (default: `forks`) ### execArgv - **CLI:** `--execArgv