diff --git a/docs/api/advanced/artifacts.md b/docs/api/advanced/artifacts.md index 67b121f9d998..3a9bbdcc81dc 100644 --- a/docs/api/advanced/artifacts.md +++ b/docs/api/advanced/artifacts.md @@ -21,7 +21,7 @@ Each artifact includes: - Optional attachments, either files or inline content associated with the artifact - A source code location indicating where the artifact was created -Vitest automatically manages attachment serialization (files are copied to [`attachmentsDir`](/config/#attachmentsdir)) and injects source location metadata, so you can focus on the data you want to record. All artifacts **must** extend from [`TestArtifactBase`](#testartifactbase) and all attachments from [`TestAttachment`](#testattachment) to be correctly handled internally. +Vitest automatically manages attachment serialization (files are copied to [`attachmentsDir`](/config/attachmentsdir)) and injects source location metadata, so you can focus on the data you want to record. All artifacts **must** extend from [`TestArtifactBase`](#testartifactbase) and all attachments from [`TestAttachment`](#testattachment) to be correctly handled internally. ## API diff --git a/docs/api/advanced/reporters.md b/docs/api/advanced/reporters.md index c4330e8fce66..12f4476d5252 100644 --- a/docs/api/advanced/reporters.md +++ b/docs/api/advanced/reporters.md @@ -140,7 +140,7 @@ The third argument indicated why the test run was finished: - `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`](/api/advanced/vitest#cancelcurrentrun) call or `Ctrl+C` was pressed in the terminal (note that it's still possible to have failed tests in this case) -If Vitest didn't find any test files to run, this event will be invoked with empty arrays of modules and errors, and the state will depend on the value of [`config.passWithNoTests`](/config/#passwithnotests). +If Vitest didn't find any test files to run, this event will be invoked with empty arrays of modules and errors, and the state will depend on the value of [`config.passWithNoTests`](/config/passwithnotests). ::: details Example ```ts @@ -324,7 +324,7 @@ function onTestCaseAnnotate( The `onTestCaseAnnotate` hook is associated with the [`context.annotate`](/guide/test-context#annotate) method. When `annotate` is invoked, Vitest serialises it and sends the same attachment to the main thread where reporter can interact with it. -If the path is specified, Vitest stores it in a separate directory (configured by [`attachmentsDir`](/config/#attachmentsdir)) and modifies the `path` property to reference it. +If the path is specified, Vitest stores it in a separate directory (configured by [`attachmentsDir`](/config/attachmentsdir)) and modifies the `path` property to reference it. ## onTestCaseArtifactRecord 4.0.11 {#ontestcaseartifactrecord} @@ -337,6 +337,6 @@ function onTestCaseArtifactRecord( The `onTestCaseArtifactRecord` hook is associated with the [`recordArtifact`](/api/advanced/artifacts#recordartifact) utility. When `recordArtifact` is invoked, Vitest serialises it and sends the same attachment to the main thread where reporter can interact with it. -If the path is specified, Vitest stores it in a separate directory (configured by [`attachmentsDir`](/config/#attachmentsdir)) and modifies the `path` property to reference it. +If the path is specified, Vitest stores it in a separate directory (configured by [`attachmentsDir`](/config/attachmentsdir)) and modifies the `path` property to reference it. Note: annotations, [even though they're built on top of this feature](/api/advanced/artifacts#relationship-with-annotations), won't hit this hook and won't appear in the `task.artifacts` array for backwards compatibility reasons until the next major version. diff --git a/docs/api/advanced/test-case.md b/docs/api/advanced/test-case.md index b91d14b46152..7e94c8e2f28c 100644 --- a/docs/api/advanced/test-case.md +++ b/docs/api/advanced/test-case.md @@ -79,7 +79,7 @@ Don't try to parse the ID. It can have a minus at the start: `-1223128da3_0_0_0` ## location -The location in the module where the test was defined. Locations are collected only if [`includeTaskLocation`](/config/#includetasklocation) is enabled in the config. Note that this option is automatically enabled if `--reporter=html`, `--ui` or `--browser` flags are used. +The location in the module where the test was defined. Locations are collected only if [`includeTaskLocation`](/config/includetasklocation) is enabled in the config. Note that this option is automatically enabled if `--reporter=html`, `--ui` or `--browser` flags are used. The location of this test will be equal to `{ line: 3, column: 1 }`: diff --git a/docs/api/advanced/test-project.md b/docs/api/advanced/test-project.md index 72eff647ab89..d0495e4fe3d3 100644 --- a/docs/api/advanced/test-project.md +++ b/docs/api/advanced/test-project.md @@ -117,7 +117,7 @@ function provide( ): void ``` -A way to provide custom values to tests in addition to [`config.provide`](/config/#provide) field. All values are validated with [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone) before they are stored, but the values on `providedContext` themselves are not cloned. +A way to provide custom values to tests in addition to [`config.provide`](/config/provide) field. All values are validated with [`structuredClone`](https://developer.mozilla.org/en-US/docs/Web/API/Window/structuredClone) before they are stored, but the values on `providedContext` themselves are not cloned. ::: code-group ```ts [node.js] @@ -137,7 +137,7 @@ const value = inject('key') The values can be provided dynamically. Provided value in tests will be updated on their next run. ::: tip -This method is also available to [global setup files](/config/#globalsetup) for cases where you cannot use the public API: +This method is also available to [global setup files](/config/globalsetup) for cases where you cannot use the public API: ```js export default function setup({ provide }) { @@ -179,7 +179,7 @@ function createSpecification( ): TestSpecification ``` -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. +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' diff --git a/docs/api/advanced/test-specification.md b/docs/api/advanced/test-specification.md index f66a4aa0091d..79e96a628a6d 100644 --- a/docs/api/advanced/test-specification.md +++ b/docs/api/advanced/test-specification.md @@ -42,10 +42,10 @@ Instance of [`TestModule`](/api/advanced/test-module) associated with the specif ## pool {#pool} -The [`pool`](/config/#pool) in which the test module will run. +The [`pool`](/config/pool) in which the test module will run. ::: danger -It's possible to have multiple pools in a single test project with [`typecheck.enabled`](/config/#typecheck-enabled). This means it's possible to have several specifications with the same `moduleId` but different `pool`. In later versions, the project will only support a single pool. +It's possible to have multiple pools in a single test project with [`typecheck.enabled`](/config/typecheck#typecheck-enabled). This means it's possible to have several specifications with the same `moduleId` but different `pool`. In later versions, the project will only support a single pool. ::: ## testLines diff --git a/docs/api/advanced/test-suite.md b/docs/api/advanced/test-suite.md index f8aa837fc62a..1e074e9da8ed 100644 --- a/docs/api/advanced/test-suite.md +++ b/docs/api/advanced/test-suite.md @@ -80,7 +80,7 @@ Don't try to parse the ID. It can have a minus at the start: `-1223128da3_0_0_0` ## location -The location in the module where the suite was defined. Locations are collected only if [`includeTaskLocation`](/config/#includetasklocation) is enabled in the config. Note that this option is automatically enabled if `--reporter=html`, `--ui` or `--browser` flags are used. +The location in the module where the suite was defined. Locations are collected only if [`includeTaskLocation`](/config/includetasklocation) is enabled in the config. Note that this option is automatically enabled if `--reporter=html`, `--ui` or `--browser` flags are used. The location of this suite will be equal to `{ line: 3, column: 1 }`: diff --git a/docs/api/advanced/vitest.md b/docs/api/advanced/vitest.md index cdf94c580bff..fd1fd33e571d 100644 --- a/docs/api/advanced/vitest.md +++ b/docs/api/advanced/vitest.md @@ -357,7 +357,7 @@ This method will gracefully cancel all ongoing tests. It will wait for started t function setGlobalTestNamePattern(pattern: string | RegExp): void ``` -This methods overrides the global [test name pattern](/config/#testnamepattern). +This methods overrides the global [test name pattern](/config/testnamepattern). ::: warning This method doesn't start running any tests. To run tests with updated pattern, call [`runTestSpecifications`](#runtestspecifications). @@ -377,7 +377,7 @@ Returns the regexp used for the global test name pattern. function resetGlobalTestNamePattern(): void ``` -This methods resets the [test name pattern](/config/#testnamepattern). It means Vitest won't skip any tests now. +This methods resets the [test name pattern](/config/testnamepattern). It means Vitest won't skip any tests now. ::: warning This method doesn't start running any tests. To run tests without a pattern, call [`runTestSpecifications`](#runtestspecifications). @@ -452,7 +452,7 @@ function exit(force = false): Promise Closes all projects and exit the process. If `force` is set to `true`, the process will exit immediately after closing the projects. -This method will also forcefully call `process.exit()` if the process is still active after [`config.teardownTimeout`](/config/#teardowntimeout) milliseconds. +This method will also forcefully call `process.exit()` if the process is still active after [`config.teardownTimeout`](/config/teardowntimeout) milliseconds. ## shouldKeepServer @@ -548,7 +548,7 @@ function createCoverageProvider(): Promise Creates a coverage provider if `coverage` is enabled in the config. This is done automatically if you are running tests with [`start`](#start) or [`init`](#init) methods. ::: warning -This method will also clean all previous reports if [`coverage.clean`](/config/#coverage-clean) is not set to `false`. +This method will also clean all previous reports if [`coverage.clean`](/config/coverage#coverage-clean) is not set to `false`. ::: ## enableCoverage 4.0.0 {#enablecoverage} diff --git a/docs/api/describe.md b/docs/api/describe.md index 0eca4f427f61..c0b4a4914c1b 100644 --- a/docs/api/describe.md +++ b/docs/api/describe.md @@ -254,7 +254,7 @@ describe.concurrent('suite', () => { - **Alias:** `suite.shuffle` -Vitest provides a way to run all tests in random order via CLI flag [`--sequence.shuffle`](/guide/cli) or config option [`sequence.shuffle`](/config/#sequence-shuffle), but if you want to have only part of your test suite to run tests in random order, you can mark it with this flag. +Vitest provides a way to run all tests in random order via CLI flag [`--sequence.shuffle`](/guide/cli) or config option [`sequence.shuffle`](/config/sequence#sequence-shuffle), but if you want to have only part of your test suite to run tests in random order, you can mark it with this flag. ```ts import { describe, test } from 'vitest' diff --git a/docs/api/hooks.md b/docs/api/hooks.md index 311f0363e91d..bae8eaa28b4f 100644 --- a/docs/api/hooks.md +++ b/docs/api/hooks.md @@ -431,7 +431,7 @@ test('performs a query', () => { ``` ::: tip -This hook is always called in reverse order and is not affected by [`sequence.hooks`](/config/#sequence-hooks) option. +This hook is always called in reverse order and is not affected by [`sequence.hooks`](/config/sequence#sequence-hooks) option. ::: ### onTestFailed diff --git a/docs/api/mock.md b/docs/api/mock.md index 860e2c0d49e4..4b9e6aefb328 100644 --- a/docs/api/mock.md +++ b/docs/api/mock.md @@ -134,7 +134,7 @@ expect(person.greet('Bob')).toBe('mocked') expect(spy.mock.calls).toEqual([['Bob']]) ``` -To automatically call this method before each test, enable the [`clearMocks`](/config/#clearmocks) setting in the configuration. +To automatically call this method before each test, enable the [`clearMocks`](/config/clearmocks) setting in the configuration. ## mockName @@ -302,7 +302,7 @@ expect(person.greet('Bob')).toBe('Hello Bob') expect(spy.mock.calls).toEqual([['Bob']]) ``` -To automatically call this method before each test, enable the [`mockReset`](/config/#mockreset) setting in the configuration. +To automatically call this method before each test, enable the [`mockReset`](/config/mockreset) setting in the configuration. ## mockRestore @@ -330,7 +330,7 @@ expect(person.greet('Bob')).toBe('Hello Bob') expect(spy.mock.calls).toEqual([]) ``` -To automatically call this method before each test, enable the [`restoreMocks`](/config/#restoremocks) setting in the configuration. +To automatically call this method before each test, enable the [`restoreMocks`](/config/restoremocks) setting in the configuration. ## mockResolvedValue diff --git a/docs/api/test.md b/docs/api/test.md index 627471bc0988..7bc7ddb6c854 100644 --- a/docs/api/test.md +++ b/docs/api/test.md @@ -618,7 +618,7 @@ test.each` ``` ::: tip -Vitest processes `$values` with Chai `format` method. If the value is too truncated, you can increase [chaiConfig.truncateThreshold](/config/#chaiconfig-truncatethreshold) in your config file. +Vitest processes `$values` with Chai `format` method. If the value is too truncated, you can increase [chaiConfig.truncateThreshold](/config/chaiconfig#chaiconfig-truncatethreshold) in your config file. ::: ## test.for diff --git a/docs/api/vi.md b/docs/api/vi.md index cd63286f3226..dfb8b1faecba 100644 --- a/docs/api/vi.md +++ b/docs/api/vi.md @@ -4,7 +4,7 @@ outline: deep # Vi -Vitest provides utility functions to help you out through its `vi` helper. You can access it globally (when [globals configuration](/config/#globals) is enabled), or import it from `vitest` directly: +Vitest provides utility functions to help you out through its `vi` helper. You can access it globally (when [globals configuration](/config/globals) is enabled), or import it from `vitest` directly: ```js import { vi } from 'vitest' @@ -42,7 +42,7 @@ It is recommended to use `vi.mock` or `vi.hoisted` only inside test files. If Vi ::: warning `vi.mock` works only for modules that were imported with the `import` keyword. It doesn't work with `require`. -In order to hoist `vi.mock`, Vitest statically analyzes your files. It indicates that `vi` that was not directly imported from the `vitest` package (for example, from some utility file) cannot be used. Use `vi.mock` with `vi` imported from `vitest`, or enable [`globals`](/config/#globals) config option. +In order to hoist `vi.mock`, Vitest statically analyzes your files. It indicates that `vi` that was not directly imported from the `vitest` package (for example, from some utility file) cannot be used. Use `vi.mock` with `vi` imported from `vitest`, or enable [`globals`](/config/globals) config option. Vitest will not mock modules that were imported inside a [setup file](/config/setupfiles) because they are cached by the time a test file is running. You can call [`vi.resetModules()`](#vi-resetmodules) inside [`vi.hoisted`](#vi-hoisted) to clear all module caches before running a test file. ::: @@ -137,7 +137,7 @@ vi.mock('./path/to/module.js', () => { ``` ::: -If there is a `__mocks__` folder alongside a file that you are mocking, and the factory is not provided, Vitest will try to find a file with the same name in the `__mocks__` subfolder and use it as an actual module. If you are mocking a dependency, Vitest will try to find a `__mocks__` folder in the [root](/config/#root) of the project (default is `process.cwd()`). You can tell Vitest where the dependencies are located through the [`deps.moduleDirectories`](/config/#deps-moduledirectories) config option. +If there is a `__mocks__` folder alongside a file that you are mocking, and the factory is not provided, Vitest will try to find a file with the same name in the `__mocks__` subfolder and use it as an actual module. If you are mocking a dependency, Vitest will try to find a `__mocks__` folder in the [root](/config/root) of the project (default is `process.cwd()`). You can tell Vitest where the dependencies are located through the [`deps.moduleDirectories`](/config/deps#deps-moduledirectories) config option. For example, you have this file structure: @@ -628,7 +628,7 @@ it('calls console.log', () => { ::: ::: tip -You can call [`vi.restoreAllMocks`](#vi-restoreallmocks) inside [`afterEach`](/api/hooks#aftereach) (or enable [`test.restoreMocks`](/config/#restoreMocks)) to restore all methods to their original implementations after every test. This will restore the original [object descriptor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), so you won't be able to change method's implementation anymore, unless you spy again: +You can call [`vi.restoreAllMocks`](#vi-restoreallmocks) inside [`afterEach`](/api/hooks#aftereach) (or enable [`test.restoreMocks`](/config/restoremocks)) to restore all methods to their original implementations after every test. This will restore the original [object descriptor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/defineProperty), so you won't be able to change method's implementation anymore, unless you spy again: ```ts const cart = { @@ -941,7 +941,7 @@ Calls every microtask that was queued by `process.nextTick`. This will also run function runAllTimers(): Vitest ``` -This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimers` will be fired. If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](/config/#faketimers-looplimit)). +This method will invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimers` will be fired. If you have an infinite interval, it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](/config/faketimers#faketimers-looplimit)). ```ts let i = 0 @@ -967,7 +967,7 @@ function runAllTimersAsync(): Promise ``` This method will asynchronously invoke every initiated timer until the timer queue is empty. It means that every timer called during `runAllTimersAsync` will be fired even asynchronous timers. If you have an infinite interval, -it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](/config/#faketimers-looplimit)). +it will throw after 10 000 tries (can be configured with [`fakeTimers.loopLimit`](/config/faketimers#faketimers-looplimit)). ```ts setTimeout(async () => { diff --git a/docs/blog/vitest-3-2.md b/docs/blog/vitest-3-2.md index f05592a75abf..0e4bff84569a 100644 --- a/docs/blog/vitest-3-2.md +++ b/docs/blog/vitest-3-2.md @@ -68,11 +68,11 @@ const test = baseTest.extend({ The file fixture is similar to using `beforeAll` and `afterAll` at the top level of the file, but it won't be called if the fixture is not used in any test. -The `worker` fixture is initiated once per worker, but note that by default Vitest creates one worker for every test, so you need to disable [isolation](/config/#isolate) to benefit from it. +The `worker` fixture is initiated once per worker, but note that by default Vitest creates one worker for every test, so you need to disable [isolation](/config/isolate) to benefit from it. ## Custom Project Name Colors -You can now set a custom [color](/config/#name) when using `projects`: +You can now set a custom [color](/config/name) when using `projects`: ::: details Config Example ```ts{6-9,14-17} @@ -192,7 +192,7 @@ it('calls console.log', () => { Vitest now provides an [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) object to the test body. You can use it to stop any resource that supports this Web API. -The signal is aborted when test times out, another test fails and [`--bail` flag](/config/#bail) is set to a non-zero value, or the user presses Ctrl+C in the terminal. +The signal is aborted when test times out, another test fails and [`--bail` flag](/config/bail) is set to a non-zero value, or the user presses Ctrl+C in the terminal. For example, you can stop a `fetch` request when tests are interrupted: @@ -204,7 +204,7 @@ it('stop request when test times out', async ({ signal }) => { ## Coverage V8 AST-aware remapping -Vitest now uses `ast-v8-to-istanbul` package developed by one of the Vitest maintainers, [AriPerkkio](https://github.com/AriPerkkio). This brings v8 coverage report in line with istanbul, but has a better performance! Enable this feature by setting [`coverage.experimentalAstAwareRemapping`](/config/#coverage-experimentalastawareremapping) to `true`. +Vitest now uses `ast-v8-to-istanbul` package developed by one of the Vitest maintainers, [AriPerkkio](https://github.com/AriPerkkio). This brings v8 coverage report in line with istanbul, but has a better performance! Enable this feature by setting [`coverage.experimentalAstAwareRemapping`](/config/coverage#coverage-experimentalastawareremapping) to `true`. We are planning to make this the default remapping mode in the next major. The old `v8-to-istanbul` will be removed completely. Feel free to join discussion at https://github.com/vitest-dev/vitest/issues/7928. @@ -267,7 +267,7 @@ expect.toBeFoo('foo') ## `sequence.groupOrder` -The new [`sequence.groupOrder`](/config/#grouporder) option controls the order in which the project runs its tests when using multiple [projects](/guide/projects). +The new [`sequence.groupOrder`](/config/sequence#sequence-grouporder) option controls the order in which the 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. diff --git a/docs/config/browser/expect.md b/docs/config/browser/expect.md index 3990ed68106d..dff6d64b9582 100644 --- a/docs/config/browser/expect.md +++ b/docs/config/browser/expect.md @@ -98,11 +98,11 @@ receives an object with the following properties: - `root: string` - Absolute path to the project's [`root`](/config/#root). + Absolute path to the project's [`root`](/config/root). - `testFileDirectory: string` - Path to the test file, relative to the project's [`root`](/config/#root). + Path to the test file, relative to the project's [`root`](/config/root). - `testFileName: string` @@ -115,7 +115,7 @@ receives an object with the following properties: - `attachmentsDir: string` - The value provided to [`attachmentsDir`](/config/#attachmentsdir), if none is + The value provided to [`attachmentsDir`](/config/attachmentsdir), if none is provided, its default value. For example, to group screenshots by browser: diff --git a/docs/config/browser/isolate.md b/docs/config/browser/isolate.md index 6663c85cb89c..5e610cdf6191 100644 --- a/docs/config/browser/isolate.md +++ b/docs/config/browser/isolate.md @@ -6,11 +6,11 @@ outline: deep # browser.isolate - **Type:** `boolean` -- **Default:** the same as [`--isolate`](/config/#isolate) +- **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. +This option is deprecated. Use [`isolate`](/config/isolate) instead. ::: diff --git a/docs/config/browser/trackunhandlederrors.md b/docs/config/browser/trackunhandlederrors.md index cab9a2d4e476..8b25e109838d 100644 --- a/docs/config/browser/trackunhandlederrors.md +++ b/docs/config/browser/trackunhandlederrors.md @@ -10,6 +10,6 @@ outline: deep 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. +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/guide/browser/index.md b/docs/guide/browser/index.md index deb2efc9f7a5..d7caf9b667de 100644 --- a/docs/guide/browser/index.md +++ b/docs/guide/browser/index.md @@ -118,7 +118,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. +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. The CLI does not print the Vite server URL automatically. You can press "b" to print the URL when running in watch mode. ::: @@ -328,7 +328,7 @@ npx vitest --browser.headless Since Vitest 3.2, if you don't have the `browser` option in your config but specify the `--browser` flag, Vitest will fail because it can't assume that config is meant for the browser and not Node.js tests. ::: -By default, Vitest will automatically open the browser UI for development. Your tests will run inside an iframe in the center. You can configure the viewport by selecting the preferred dimensions, calling `page.viewport` inside the test, or setting default values in [the config](/config/#browser-viewport). +By default, Vitest will automatically open the browser UI for development. Your tests will run inside an iframe in the center. You can configure the viewport by selecting the preferred dimensions, calling `page.viewport` inside the test, or setting default values in [the config](/config/browser/viewport). ## Headless diff --git a/docs/guide/browser/multiple-setups.md b/docs/guide/browser/multiple-setups.md index ee9ca4be5718..5f66eb0cefa1 100644 --- a/docs/guide/browser/multiple-setups.md +++ b/docs/guide/browser/multiple-setups.md @@ -74,7 +74,7 @@ test('ratio works', () => { ``` ::: -In this example Vitest will run all tests in `chromium` browser, but execute a `'./ratio-setup.ts'` file only in the first configuration and inject a different `ratio` value depending on the [`provide` field](/config/#provide). +In this example Vitest will run all tests in `chromium` browser, but execute a `'./ratio-setup.ts'` file only in the first configuration and inject a different `ratio` value depending on the [`provide` field](/config/provide). ::: warning Note that you need to define the custom `name` value if you are using the same browser name because Vitest will assign the `browser` as the project name otherwise. diff --git a/docs/guide/cli-generated.md b/docs/guide/cli-generated.md index 5b8acd881de7..b449a9ad481b 100644 --- a/docs/guide/cli-generated.md +++ b/docs/guide/cli-generated.md @@ -165,7 +165,7 @@ Directory to write coverage report to (default: ./coverage) - **CLI:** `--coverage.reporter ` - **Config:** [coverage.reporter](/config/coverage#coverage-reporter) -Coverage reporters to use. Visit [`coverage.reporter`](/config/#coverage-reporter) for more information (default: `["text", "html", "clover", "json"]`) +Coverage reporters to use. Visit [`coverage.reporter`](/config/coverage#coverage-reporter) for more information (default: `["text", "html", "clover", "json"]`) ### coverage.reportOnFailure @@ -511,7 +511,7 @@ Set the randomization seed. This option will have no effect if `--sequence.shuff - **CLI:** `--sequence.hooks ` - **Config:** [sequence.hooks](/config/sequence#sequence-hooks) -Changes the order in which hooks are executed. Accepted values are: "stack", "list" and "parallel". Visit [`sequence.hooks`](/config/#sequence-hooks) for more information (default: `"parallel"`) +Changes the order in which hooks are executed. Accepted values are: "stack", "list" and "parallel". Visit [`sequence.hooks`](/config/sequence#sequence-hooks) for more information (default: `"parallel"`) ### sequence.setupFiles diff --git a/docs/guide/cli.md b/docs/guide/cli.md index 928709ec10e4..61d82db36b5b 100644 --- a/docs/guide/cli.md +++ b/docs/guide/cli.md @@ -198,7 +198,7 @@ To run tests against changes made in the last commit, you can use `--changed HEA When used with code coverage the report will contain only the files that were related to the changes. -If paired with the [`forceRerunTriggers`](/config/#forcereruntriggers) config option it will run the whole test suite if at least one of the files listed in the `forceRerunTriggers` list changes. By default, changes to the Vitest config file and `package.json` will always rerun the whole suite. +If paired with the [`forceRerunTriggers`](/config/forcereruntriggers) config option it will run the whole test suite if at least one of the files listed in the `forceRerunTriggers` list changes. By default, changes to the Vitest config file and `package.json` will always rerun the whole suite. ### shard diff --git a/docs/guide/common-errors.md b/docs/guide/common-errors.md index d19d303a642b..5c22045bbcb3 100644 --- a/docs/guide/common-errors.md +++ b/docs/guide/common-errors.md @@ -28,7 +28,7 @@ Or rewrite your path to not be relative to root: + import helpers from '../src/helpers' ``` -3. Make sure you don't have relative [aliases](/config/#alias). Vite treats them as relative to the file where the import is instead of the root. +3. Make sure you don't have relative [aliases](/config/alias). Vite treats them as relative to the file where the import is instead of the root. ```ts import { defineConfig } from 'vitest/config' diff --git a/docs/guide/coverage.md b/docs/guide/coverage.md index 4bb054b638c0..c317853ed1dd 100644 --- a/docs/guide/coverage.md +++ b/docs/guide/coverage.md @@ -138,7 +138,7 @@ globalThis.__VITEST_COVERAGE__[filename] = coverage // [!code ++] ## Coverage Setup ::: tip -All coverage options are listed in [Coverage Config Reference](/config/#coverage). +All coverage options are listed in [Coverage Config Reference](/config/coverage). ::: To test with coverage enabled, you can pass the `--coverage` flag in CLI or set `coverage.enabled` in `vitest.config.ts`: @@ -167,10 +167,10 @@ export default defineConfig({ ## Including and Excluding Files from Coverage Report -You can define what files are shown in coverage report by configuring [`coverage.include`](/config/#coverage-include) and [`coverage.exclude`](/config/#coverage-exclude). +You can define what files are shown in coverage report by configuring [`coverage.include`](/config/coverage#coverage-include) and [`coverage.exclude`](/config/coverage#coverage-exclude). By default Vitest will show only files that were imported during test run. -To include uncovered files in the report, you'll need to configure [`coverage.include`](/config/#coverage-include) with a pattern that will pick your source files: +To include uncovered files in the report, you'll need to configure [`coverage.include`](/config/coverage#coverage-include) with a pattern that will pick your source files: ::: code-group ```ts [vitest.config.ts] {6} @@ -204,7 +204,7 @@ export default defineConfig({ ``` ::: -To exclude files that are matching `coverage.include`, you can define an additional [`coverage.exclude`](/config/#coverage-exclude): +To exclude files that are matching `coverage.include`, you can define an additional [`coverage.exclude`](/config/coverage#coverage-exclude): ::: code-group ```ts [vitest.config.ts] {7} diff --git a/docs/guide/environment.md b/docs/guide/environment.md index 6c06964e4832..5abdc011ad29 100644 --- a/docs/guide/environment.md +++ b/docs/guide/environment.md @@ -4,7 +4,7 @@ title: Test Environment | Guide # Test Environment -Vitest provides [`environment`](/config/#environment) option to run code inside a specific environment. You can modify how environment behaves with [`environmentOptions`](/config/#environmentoptions) option. +Vitest provides [`environment`](/config/environment) option to run code inside a specific environment. You can modify how environment behaves with [`environmentOptions`](/config/environmentoptions) option. By default, you can use these environments: @@ -14,7 +14,7 @@ By default, you can use these environments: - `edge-runtime` emulates Vercel's [edge-runtime](https://edge-runtime.vercel.app/), uses [`@edge-runtime/vm`](https://www.npmjs.com/package/@edge-runtime/vm) package ::: info -When using `jsdom` or `happy-dom` environments, Vitest follows the same rules that Vite does when importing [CSS](https://vitejs.dev/guide/features.html#css) and [assets](https://vitejs.dev/guide/features.html#static-assets). If importing external dependency fails with `unknown extension .css` error, you need to inline the whole import chain manually by adding all packages to [`server.deps.inline`](/config/#server-deps-inline). For example, if the error happens in `package-3` in this import chain: `source code -> package-1 -> package-2 -> package-3`, you need to add all three packages to `server.deps.inline`. +When using `jsdom` or `happy-dom` environments, Vitest follows the same rules that Vite does when importing [CSS](https://vitejs.dev/guide/features.html#css) and [assets](https://vitejs.dev/guide/features.html#static-assets). If importing external dependency fails with `unknown extension .css` error, you need to inline the whole import chain manually by adding all packages to [`server.deps.inline`](/config/server#inline). For example, if the error happens in `package-3` in this import chain: `source code -> package-1 -> package-2 -> package-3`, you need to add all three packages to `server.deps.inline`. The `require` of CSS and assets inside the external dependencies are resolved automatically. ::: diff --git a/docs/guide/features.md b/docs/guide/features.md index a0dd58de27e0..9b4cbdd6a2d6 100644 --- a/docs/guide/features.md +++ b/docs/guide/features.md @@ -39,7 +39,7 @@ Out-of-the-box ES Module / TypeScript / JSX support / PostCSS ## Threads By default Vitest runs test files in [multiple processes](/guide/parallelism) using [`node:child_process`](https://nodejs.org/api/child_process.html), allowing tests to run simultaneously. If you want to speed up your test suite even further, consider enabling `--pool=threads` to run tests using [`node:worker_threads`](https://nodejs.org/api/worker_threads.html) (beware that some packages might not work with this setup). -To run tests in a single thread or process, see [`fileParallelism`](/config/#fileParallelism). +To run tests in a single thread or process, see [`fileParallelism`](/config/fileparallelism). Vitest also isolates each file's environment so env mutations in one file don't affect others. Isolation can be disabled by passing `--no-isolate` to the CLI (trading correctness for run performance). @@ -102,7 +102,7 @@ Learn more at [Snapshot](/guide/snapshot). [Chai](https://www.chaijs.com/) is built-in for assertions with [Jest `expect`](https://jestjs.io/docs/expect)-compatible APIs. -Notice that if you are using third-party libraries that add matchers, setting [`test.globals`](/config/#globals) to `true` will provide better compatibility. +Notice that if you are using third-party libraries that add matchers, setting [`test.globals`](/config/globals) to `true` will provide better compatibility. ## Mocking @@ -292,7 +292,7 @@ window.addEventListener('unhandledrejection', () => { ``` ::: -Alternatively, you can also ignore reported errors with a [`dangerouslyIgnoreUnhandledErrors`](/config/#dangerouslyignoreunhandlederrors) option. Vitest will still report them, but they won't affect the test result (exit code won't be changed). +Alternatively, you can also ignore reported errors with a [`dangerouslyIgnoreUnhandledErrors`](/config/dangerouslyignoreunhandlederrors) option. Vitest will still report them, but they won't affect the test result (exit code won't be changed). If you need to test that error was not caught, you can create a test that looks like this: diff --git a/docs/guide/filtering.md b/docs/guide/filtering.md index 93e8aa13d006..56fa545dd8e1 100644 --- a/docs/guide/filtering.md +++ b/docs/guide/filtering.md @@ -51,7 +51,7 @@ $ vitest basic/foo.test.ts:10-25 # ❌ ## Specifying a Timeout -You can optionally pass a timeout in milliseconds as a third argument to tests. The default is [5 seconds](/config/#testtimeout). +You can optionally pass a timeout in milliseconds as a third argument to tests. The default is [5 seconds](/config/testtimeout). ```ts import { test } from 'vitest' diff --git a/docs/guide/improving-performance.md b/docs/guide/improving-performance.md index 821837f06238..371fbd770b46 100644 --- a/docs/guide/improving-performance.md +++ b/docs/guide/improving-performance.md @@ -2,13 +2,13 @@ ## Test Isolation -By default Vitest runs every test file in an isolated environment based on the [pool](/config/#pool): +By default Vitest runs every test file in an isolated environment based on the [pool](/config/pool): - `threads` pool runs every test file in a separate [`Worker`](https://nodejs.org/api/worker_threads.html#class-worker) - `forks` pool runs every test file in a separate [forked child process](https://nodejs.org/api/child_process.html#child_processforkmodulepath-args-options) - `vmThreads` pool runs every test file in a separate [VM context](https://nodejs.org/api/vm.html#vmcreatecontextcontextobject-options), but it uses workers for parallelism -This greatly increases test times, which might not be desirable for projects that don't rely on side effects and properly cleanup their state (which is usually true for projects with `node` environment). In this case disabling isolation will improve the speed of your tests. To do that, you can provide `--no-isolate` flag to the CLI or set [`test.isolate`](/config/#isolate) property in the config to `false`. +This greatly increases test times, which might not be desirable for projects that don't rely on side effects and properly cleanup their state (which is usually true for projects with `node` environment). In this case disabling isolation will improve the speed of your tests. To do that, you can provide `--no-isolate` flag to the CLI or set [`test.isolate`](/config/isolate) property in the config to `false`. ::: code-group ```bash [CLI] @@ -56,7 +56,7 @@ export default defineConfig({ If you are using `vmThreads` pool, you cannot disable isolation. Use `threads` pool instead to improve your tests performance. ::: -For some projects, it might also be desirable to disable parallelism to improve startup time. To do that, provide `--no-file-parallelism` flag to the CLI or set [`test.fileParallelism`](/config/#fileparallelism) property in the config to `false`. +For some projects, it might also be desirable to disable parallelism to improve startup time. To do that, provide `--no-file-parallelism` flag to the CLI or set [`test.fileParallelism`](/config/fileparallelism) property in the config to `false`. ::: code-group ```bash [CLI] @@ -75,7 +75,7 @@ export default defineConfig({ ## Limiting Directory Search -You can limit the working directory when Vitest searches for files using [`test.dir`](/config/#test-dir) option. This should make the search faster if you have unrelated folders and files in the root directory. +You can limit the working directory when Vitest searches for files using [`test.dir`](/config/dir) option. This should make the search faster if you have unrelated folders and files in the root directory. ## Pool diff --git a/docs/guide/migration.md b/docs/guide/migration.md index a6fcfa929de6..585d8260930a 100644 --- a/docs/guide/migration.md +++ b/docs/guide/migration.md @@ -145,7 +145,7 @@ Note that now if you provide an arrow function, you will get [` is no Alongside new features like supporting constructors, Vitest 4 creates mocks differently to address several module mocking issues that we received over the years. This release attempts to make module spies less confusing, especially when working with classes. - `vi.fn().getMockName()` now returns `vi.fn()` by default instead of `spy`. This can affect snapshots with mocks - the name will be changed from `[MockFunction spy]` to `[MockFunction]`. Spies created with `vi.spyOn` will keep using the original name by default for better debugging experience -- `vi.restoreAllMocks` no longer resets the state of spies and only restores spies created manually with `vi.spyOn`, automocks are no longer affected by this function (this also affects the config option [`restoreMocks`](/config/#restoremocks)). Note that `.mockRestore` will still reset the mock implementation and clear the state +- `vi.restoreAllMocks` no longer resets the state of spies and only restores spies created manually with `vi.spyOn`, automocks are no longer affected by this function (this also affects the config option [`restoreMocks`](/config/restoremocks)). Note that `.mockRestore` will still reset the mock implementation and clear the state - Calling `vi.spyOn` on a mock now returns the same mock - `mock.settledResults` are now populated immediately on function invocation with an `'incomplete'` result. When the promise is finished, the type is changed according to the result. - Automocked instance methods are now properly isolated, but share a state with the prototype. Overriding the prototype implementation will always affect instance methods unless the methods have a custom mock implementation of their own. Calling `.mockReset` on the mock also no longer breaks that inheritance. @@ -212,9 +212,9 @@ Module Runner is a successor to `vite-node` implemented directly in Vite. Vitest - `vitest/execute` entry point was removed. It was always meant to be internal - [Custom environments](/guide/environment) no longer need to provide a `transformMode` property. Instead, provide `viteEnvironment`. If it is not provided, Vitest will use the environment name to transform files on the server (see [`server.environments`](https://vite.dev/guide/api-environment-instances.html)) - `vite-node` is no longer a dependency of Vitest -- `deps.optimizer.web` was renamed to [`deps.optimizer.client`](/config/#deps-optimizer-client). You can also use any custom names to apply optimizer configs when using other server environments +- `deps.optimizer.web` was renamed to [`deps.optimizer.client`](/config/deps#deps-client). You can also use any custom names to apply optimizer configs when using other server environments -Vite has its own externalization mechanism, but we decided to keep using the old one to reduce the amount of breaking changes. You can keep using [`server.deps`](/config/#server-deps) to inline or externalize packages. +Vite has its own externalization mechanism, but we decided to keep using the old one to reduce the amount of breaking changes. You can keep using [`server.deps`](/config/server#deps) to inline or externalize packages. This update should not be noticeable unless you rely on advanced features mentioned above. @@ -439,7 +439,7 @@ export default defineConfig({ ### Snapshots using Custom Elements Print the Shadow Root -In Vitest 4.0 snapshots that include custom elements will print the shadow root contents. To restore the previous behavior, set the [`printShadowRoot` option](/config/#snapshotformat) to `false`. +In Vitest 4.0 snapshots that include custom elements will print the shadow root contents. To restore the previous behavior, set the [`printShadowRoot` option](/config/snapshotformat) to `false`. ```js{15-22} // before Vitest 4.0 @@ -500,7 +500,7 @@ Vitest has been designed with a Jest compatible API, in order to make the migrat ### Globals as a Default -Jest has their [globals API](https://jestjs.io/docs/api) enabled by default. Vitest does not. You can either enable globals via [the `globals` configuration setting](/config/#globals) or update your code to use imports from the `vitest` module instead. +Jest has their [globals API](https://jestjs.io/docs/api) enabled by default. Vitest does not. You can either enable globals via [the `globals` configuration setting](/config/globals) or update your code to use imports from the `vitest` module instead. If you decide to keep globals disabled, be aware that common libraries like [`testing-library`](https://testing-library.com/) will not run auto DOM [cleanup](https://testing-library.com/docs/svelte-testing-library/api/#cleanup). @@ -552,7 +552,7 @@ const { cloneDeep } = await vi.importActual('lodash/cloneDeep') // [!code ++] ### Extends mocking to external libraries -Where Jest does it by default, when mocking a module and wanting this mocking to be extended to other external libraries that use the same module, you should explicitly tell which 3rd-party library you want to be mocked, so the external library would be part of your source code, by using [server.deps.inline](/config/#server-deps-inline). +Where Jest does it by default, when mocking a module and wanting this mocking to be extended to other external libraries that use the same module, you should explicitly tell which 3rd-party library you want to be mocked, so the external library would be part of your source code, by using [server.deps.inline](/config/server#inline). ``` server.deps.inline: ["lib-name"] @@ -590,7 +590,7 @@ beforeEach(() => setActivePinia(createTestingPinia())) // [!code --] beforeEach(() => { setActivePinia(createTestingPinia()) }) // [!code ++] ``` -In Jest hooks are called sequentially (one after another). By default, Vitest runs hooks in a stack. To use Jest's behavior, update [`sequence.hooks`](/config/#sequence-hooks) option: +In Jest hooks are called sequentially (one after another). By default, Vitest runs hooks in a stack. To use Jest's behavior, update [`sequence.hooks`](/config/sequence#sequence-hooks) option: ```ts export default defineConfig({ @@ -627,7 +627,7 @@ vi.setConfig({ testTimeout: 5_000 }) // [!code ++] ### Vue Snapshots -This is not a Jest-specific feature, but if you previously were using Jest with vue-cli preset, you will need to install [`jest-serializer-vue`](https://github.com/eddyerburgh/jest-serializer-vue) package, and specify it in [`snapshotSerializers`](/config/#snapshotserializers): +This is not a Jest-specific feature, but if you previously were using Jest with vue-cli preset, you will need to install [`jest-serializer-vue`](https://github.com/eddyerburgh/jest-serializer-vue) package, and specify it in [`snapshotSerializers`](/config/snapshotserializers): ```js [vitest.config.js] import { defineConfig } from 'vitest/config' @@ -811,7 +811,7 @@ vi.useRealTimers() ### Key Differences -1. **Globals**: Mocha provides globals by default. In Vitest, either import from `vitest` or enable [`globals`](/config/#globals) config +1. **Globals**: Mocha provides globals by default. In Vitest, either import from `vitest` or enable [`globals`](/config/globals) config 2. **Assertion style**: You can use both Chai-style (`expect(spy).to.have.been.called`) and Jest-style (`expect(spy).toHaveBeenCalled()`) 3. **Parallel execution**: Vitest runs tests in parallel by default, Mocha runs sequentially diff --git a/docs/guide/mocking.md b/docs/guide/mocking.md index a22260d0666f..a4684c0c7629 100644 --- a/docs/guide/mocking.md +++ b/docs/guide/mocking.md @@ -5,7 +5,7 @@ outline: false # Mocking -When writing tests it's only a matter of time before you need to create a "fake" version of an internal — or external — service. This is commonly referred to as **mocking**. Vitest provides utility functions to help you out through its `vi` helper. You can import it from `vitest` or access it globally if [`global` configuration](/config/#globals) is enabled. +When writing tests it's only a matter of time before you need to create a "fake" version of an internal — or external — service. This is commonly referred to as **mocking**. Vitest provides utility functions to help you out through its `vi` helper. You can import it from `vitest` or access it globally if [`global` configuration](/config/globals) is enabled. ::: warning Always remember to clear or restore mocks before or after each test run to undo mock state changes between runs! See [`mockReset`](/api/mock#mockreset) docs for more info. @@ -182,7 +182,7 @@ vi.useRealTimers() ### Mock a global variable -You can set global variable by assigning a value to `globalThis` or using [`vi.stubGlobal`](/api/vi#vi-stubglobal) helper. When using `vi.stubGlobal`, it will **not** automatically reset between different tests, unless you enable [`unstubGlobals`](/config/#unstubglobals) config option or call [`vi.unstubAllGlobals`](/api/vi#vi-unstuballglobals). +You can set global variable by assigning a value to `globalThis` or using [`vi.stubGlobal`](/api/vi#vi-stubglobal) helper. When using `vi.stubGlobal`, it will **not** automatically reset between different tests, unless you enable [`unstubGlobals`](/config/unstubglobals) config option or call [`vi.unstubAllGlobals`](/api/vi#vi-unstuballglobals). ```ts vi.stubGlobal('__VERSION__', '1.0.0') @@ -213,7 +213,7 @@ it('changes value', () => { }) ``` -2. If you want to automatically reset the value(s), you can use the `vi.stubEnv` helper with the [`unstubEnvs`](/config/#unstubenvs) config option enabled (or call [`vi.unstubAllEnvs`](/api/vi#vi-unstuballenvs) manually in a `beforeEach` hook): +2. If you want to automatically reset the value(s), you can use the `vi.stubEnv` helper with the [`unstubEnvs`](/config/unstubenvs) config option enabled (or call [`vi.unstubAllEnvs`](/api/vi#vi-unstuballenvs) manually in a `beforeEach` hook): ```ts import { expect, it, vi } from 'vitest' diff --git a/docs/guide/mocking/globals.md b/docs/guide/mocking/globals.md index 28e84332d3b7..12674c490235 100644 --- a/docs/guide/mocking/globals.md +++ b/docs/guide/mocking/globals.md @@ -2,7 +2,7 @@ You can mock global variables that are not present with `jsdom` or `node` by using [`vi.stubGlobal`](/api/vi#vi-stubglobal) helper. It will put the value of the global variable into a `globalThis` object. -By default, Vitest does not reset these globals, but you can turn on the [`unstubGlobals`](/config/#unstubglobals) option in your config to restore the original values after each test or call [`vi.unstubAllGlobals()`](/api/vi#vi-unstuballglobals) manually. +By default, Vitest does not reset these globals, but you can turn on the [`unstubGlobals`](/config/unstubglobals) option in your config to restore the original values after each test or call [`vi.unstubAllGlobals()`](/api/vi#vi-unstuballglobals) manually. ```ts import { vi } from 'vitest' diff --git a/docs/guide/mocking/modules.md b/docs/guide/mocking/modules.md index 171fcde7614f..a14e2e85df46 100644 --- a/docs/guide/mocking/modules.md +++ b/docs/guide/mocking/modules.md @@ -236,7 +236,7 @@ Vitest supports mocking virtual modules. These modules don't exist on the file s By default, Vitest will fail transforming files if it cannot find the source of the import. To bypass this, you need to specify it in your config. You can either always redirect the import to a file, or just signal Vite to ignore it and use the `vi.mock` factory to define its exports. -To redirect the import, use [`test.alias`](/config/#alias) config option: +To redirect the import, use [`test.alias`](/config/alias) config option: ```ts [vitest.config.ts] import { defineConfig } from 'vitest/config' diff --git a/docs/guide/parallelism.md b/docs/guide/parallelism.md index 518e2d9dfee2..c5772b20865d 100644 --- a/docs/guide/parallelism.md +++ b/docs/guide/parallelism.md @@ -12,15 +12,15 @@ By default, Vitest runs _test files_ in parallel. Depending on the specified `po - `forks` (the default) and `vmForks` run tests in different [child processes](https://nodejs.org/api/child_process.html) - `threads` and `vmThreads` run tests in different [worker threads](https://nodejs.org/api/worker_threads.html) -Both "child processes" and "worker threads" are referred to as "workers". You can configure the number of running workers with [`maxWorkers`](/config/#maxworkers) option. +Both "child processes" and "worker threads" are referred to as "workers". You can configure the number of running workers with [`maxWorkers`](/config/maxworkers) option. -If you have a lot of tests, it is usually faster to run them in parallel, but it also depends on the project, the environment and [isolation](/config/#isolate) state. To disable file parallelisation, you can set [`fileParallelism`](/config/#fileparallelism) to `false`. To learn more about possible performance improvements, read the [Performance Guide](/guide/improving-performance). +If you have a lot of tests, it is usually faster to run them in parallel, but it also depends on the project, the environment and [isolation](/config/isolate) state. To disable file parallelisation, you can set [`fileParallelism`](/config/fileparallelism) to `false`. To learn more about possible performance improvements, read the [Performance Guide](/guide/improving-performance). ## Test Parallelism Unlike _test files_, Vitest runs _tests_ in sequence. This means that tests inside a single test file will run in the order they are defined. -Vitest supports the [`concurrent`](/api/test#test-concurrent) option to run tests together. If this option is set, Vitest will group concurrent tests in the same _file_ (the number of simultaneously running tests depends on the [`maxConcurrency`](/config/#maxconcurrency) option) and run them with [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). +Vitest supports the [`concurrent`](/api/test#test-concurrent) option to run tests together. If this option is set, Vitest will group concurrent tests in the same _file_ (the number of simultaneously running tests depends on the [`maxConcurrency`](/config/maxconcurrency) option) and run them with [`Promise.all`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all). Vitest doesn't perform any smart analysis and doesn't create additional workers to run these tests. This means that the performance of your tests will improve only if you rely heavily on asynchronous operations. For example, these tests will still run one after another even though the `concurrent` option is specified. This is because they are synchronous: @@ -34,4 +34,4 @@ test.concurrent('the second test', () => { }) ``` -If you wish to run all tests concurrently, you can set the [`sequence.concurrent`](/config/#sequence-concurrent) option to `true`. +If you wish to run all tests concurrently, you can set the [`sequence.concurrent`](/config/sequence#sequence-concurrent) option to `true`. diff --git a/docs/guide/profiling-test-performance.md b/docs/guide/profiling-test-performance.md index 627abba19f43..da6a0952e5d8 100644 --- a/docs/guide/profiling-test-performance.md +++ b/docs/guide/profiling-test-performance.md @@ -19,7 +19,7 @@ When you run Vitest it reports multiple time metrics of your tests: - Setup: Time spent for running the [`setupFiles`](/config/setupfiles) files. - Import: Time it took to import your test files and their dependencies. This also includes the time spent collecting all tests. Note that this doesn't include dynamic imports inside of tests. - Tests: Time spent for actually running the test cases. -- Environment: Time spent for setting up the test [`environment`](/config/#environment), for example JSDOM. +- Environment: Time spent for setting up the test [`environment`](/config/environment), for example JSDOM. ## Test Runner @@ -57,7 +57,7 @@ See [Profiling | Examples](https://github.com/vitest-dev/vitest/tree/main/exampl ## Main Thread -Profiling main thread is useful for debugging Vitest's Vite usage and [`globalSetup`](/config/#globalsetup) files. +Profiling main thread is useful for debugging Vitest's Vite usage and [`globalSetup`](/config/globalsetup) files. This is also where your Vite plugins are running. :::tip @@ -150,7 +150,7 @@ $ DEBUG=vitest:coverage vitest --run --coverage This profiling approach is great for detecting large files that are accidentally picked by coverage providers. For example if your configuration is accidentally including large built minified Javascript files in code coverage, they should appear in logs. -In these cases you might want to adjust your [`coverage.include`](/config/#coverage-include) and [`coverage.exclude`](/config/#coverage-exclude) options. +In these cases you might want to adjust your [`coverage.include`](/config/coverage#coverage-include) and [`coverage.exclude`](/config/coverage#coverage-exclude) options. ## Inspecting Profiling Records diff --git a/docs/guide/reporters.md b/docs/guide/reporters.md index 0b807789191e..9d8292409ee9 100644 --- a/docs/guide/reporters.md +++ b/docs/guide/reporters.md @@ -5,7 +5,7 @@ outline: deep # Reporters -Vitest provides several built-in reporters to display test output in different formats, as well as the ability to use custom reporters. You can select different reporters either by using the `--reporter` command line option, or by including a `reporters` property in your [configuration file](/config/#reporters). If no reporter is specified, Vitest will use the `default` reporter as described below. +Vitest provides several built-in reporters to display test output in different formats, as well as the ability to use custom reporters. You can select different reporters either by using the `--reporter` command line option, or by including a `reporters` property in your [configuration file](/config/reporters). If no reporter is specified, Vitest will use the `default` reporter as described below. Using reporters via command line: @@ -40,7 +40,7 @@ export default defineConfig({ ## Reporter Output -By default, Vitest's reporters will print their output to the terminal. When using the `json`, `html` or `junit` reporters, you can instead write your tests' output to a file by including an `outputFile` [configuration option](/config/#outputfile) either in your Vite configuration file or via CLI. +By default, Vitest's reporters will print their output to the terminal. When using the `json`, `html` or `junit` reporters, you can instead write your tests' output to a file by including an `outputFile` [configuration option](/config/outputfile) either in your Vite configuration file or via CLI. :::code-group ```bash [CLI] @@ -294,7 +294,7 @@ Example terminal output for a passing test suite: ### JUnit Reporter -Outputs a report of the test results in JUnit XML format. Can either be printed to the terminal or written to an XML file using the [`outputFile`](/config/#outputfile) configuration option. +Outputs a report of the test results in JUnit XML format. Can either be printed to the terminal or written to an XML file using the [`outputFile`](/config/outputfile) configuration option. :::code-group ```bash [CLI] @@ -345,7 +345,7 @@ export default defineConfig({ ### JSON Reporter -Generates a report of the test results in a JSON format compatible with Jest's `--json` option. Can either be printed to the terminal or written to a file using the [`outputFile`](/config/#outputfile) configuration option. +Generates a report of the test results in a JSON format compatible with Jest's `--json` option. Can either be printed to the terminal or written to a file using the [`outputFile`](/config/outputfile) configuration option. :::code-group ```bash [CLI] @@ -417,7 +417,7 @@ Since Vitest 3, the JSON reporter includes coverage information in `coverageMap` Generates an HTML file to view test results through an interactive [GUI](/guide/ui). After the file has been generated, Vitest will keep a local development server running and provide a link to view the report in a browser. -Output file can be specified using the [`outputFile`](/config/#outputfile) configuration option. If no `outputFile` option is provided, a new HTML file will be created. +Output file can be specified using the [`outputFile`](/config/outputfile) configuration option. If no `outputFile` option is provided, a new HTML file will be created. :::code-group ```bash [CLI] diff --git a/docs/guide/snapshot.md b/docs/guide/snapshot.md index 1d5860d77e1a..b9a3ba6405d7 100644 --- a/docs/guide/snapshot.md +++ b/docs/guide/snapshot.md @@ -136,7 +136,7 @@ expect.addSnapshotSerializer({ }) ``` -We also support [snapshotSerializers](/config/#snapshotserializers) option to implicitly add custom serializers. +We also support [snapshotSerializers](/config/snapshotserializers) option to implicitly add custom serializers. ```ts [path/to/custom-serializer.ts] import { SnapshotSerializer } from 'vitest' diff --git a/docs/guide/test-context.md b/docs/guide/test-context.md index f416aa474f84..86d99b523f60 100644 --- a/docs/guide/test-context.md +++ b/docs/guide/test-context.md @@ -94,7 +94,7 @@ function annotate( ): Promise ``` -Add a [test annotation](/guide/test-annotations) that will be displayed by your [reporter](/config/#reporters). +Add a [test annotation](/guide/test-annotations) that will be displayed by your [reporter](/config/reporters). ```ts test('annotations API', async ({ annotate }) => { @@ -109,7 +109,7 @@ An [`AbortSignal`](https://developer.mozilla.org/en-US/docs/Web/API/AbortSignal) - Test times out - User manually cancelled the test run with Ctrl+C - [`vitest.cancelCurrentRun`](/api/advanced/vitest#cancelcurrentrun) was called programmatically -- Another test failed in parallel and the [`bail`](/config/#bail) flag is set +- Another test failed in parallel and the [`bail`](/config/bail) flag is set ```ts it('stop request when test times out', async ({ signal }) => { @@ -568,7 +568,7 @@ const test = baseTest ``` ::: info -By default, every file runs in a separate worker, so `file` and `worker` scopes work the same way. However, if you disable [isolation](/config/#isolate), then the number of workers is limited by [`maxWorkers`](/config/#maxworkers), and worker-scoped fixtures will be shared across files running in the same worker. +By default, every file runs in a separate worker, so `file` and `worker` scopes work the same way. However, if you disable [isolation](/config/isolate), then the number of workers is limited by [`maxWorkers`](/config/maxworkers), and worker-scoped fixtures will be shared across files running in the same worker. When running tests in `vmThreads` or `vmForks`, `scope: 'worker'` works the same way as `scope: 'file'` because each file has its own VM context. ::: @@ -640,7 +640,7 @@ This provides the same compile-time safety as the builder pattern, catching scop ### Default Fixture (Injected) -Since Vitest 3, you can provide different values in different [projects](/guide/projects). To enable this, pass `{ injected: true }` in the options. If the key is not specified in the [project configuration](/config/#provide), the default value will be used. +Since Vitest 3, you can provide different values in different [projects](/guide/projects). To enable this, pass `{ injected: true }` in the options. If the key is not specified in the [project configuration](/config/provide), the default value will be used. :::code-group ```ts [fixtures.test.ts] diff --git a/docs/guide/testing-types.md b/docs/guide/testing-types.md index d6933de4d63b..3ba975ec6d5e 100644 --- a/docs/guide/testing-types.md +++ b/docs/guide/testing-types.md @@ -10,9 +10,9 @@ title: Testing Types | Guide ::: -Vitest allows you to write tests for your types, using `expectTypeOf` or `assertType` syntaxes. By default all tests inside `*.test-d.ts` files are considered type tests, but you can change it with [`typecheck.include`](/config/#typecheck-include) config option. +Vitest allows you to write tests for your types, using `expectTypeOf` or `assertType` syntaxes. By default all tests inside `*.test-d.ts` files are considered type tests, but you can change it with [`typecheck.include`](/config/typecheck#typecheck-include) config option. -Under the hood Vitest calls `tsc` or `vue-tsc`, depending on your config, and parses results. Vitest will also print out type errors in your source code, if it finds any. You can disable it with [`typecheck.ignoreSourceErrors`](/config/#typecheck-ignoresourceerrors) config option. +Under the hood Vitest calls `tsc` or `vue-tsc`, depending on your config, and parses results. Vitest will also print out type errors in your source code, if it finds any. You can disable it with [`typecheck.ignoreSourceErrors`](/config/typecheck#typecheck-ignoresourceerrors) config option. Keep in mind that Vitest doesn't run these files, they are only statically analyzed by the compiler. Meaning, that if you use a dynamic name or `test.each` or `test.for`, the test name will not be evaluated - it will be displayed as is. @@ -111,7 +111,7 @@ assertType(answer) ``` ::: tip -When using `@ts-expect-error` syntax, you might want to make sure that you didn't make a typo. You can do that by including your type files in [`test.include`](/config/#include) config option, so Vitest will also actually *run* these tests and fail with `ReferenceError`. +When using `@ts-expect-error` syntax, you might want to make sure that you didn't make a typo. You can do that by including your type files in [`test.include`](/config/include) config option, so Vitest will also actually *run* these tests and fail with `ReferenceError`. This will pass, because it expects an error, but the word “answer” has a typo, so it's a false positive error: @@ -123,7 +123,7 @@ assertType(answr) ## Run Typechecking -To enable typechecking, just add [`--typecheck`](/config/#typecheck) flag to your Vitest command in `package.json`: +To enable typechecking, just add [`--typecheck`](/config/typecheck) flag to your Vitest command in `package.json`: ```json [package.json] { diff --git a/docs/guide/ui.md b/docs/guide/ui.md index 70e930997a29..440f7c78465b 100644 --- a/docs/guide/ui.md +++ b/docs/guide/ui.md @@ -50,7 +50,7 @@ To preview your HTML report, you can use the [vite preview](https://vitejs.dev/g npx vite preview --outDir ./html ``` -You can configure output with [`outputFile`](/config/#outputfile) config option. You need to specify `.html` path there. For example, `./html/index.html` is the default value. +You can configure output with [`outputFile`](/config/outputfile) config option. You need to specify `.html` path there. For example, `./html/index.html` is the default value. ::: ## Module Graph diff --git a/packages/vitest/src/node/cli/cli-config.ts b/packages/vitest/src/node/cli/cli-config.ts index 2eb744f295c4..a1d982da003b 100644 --- a/packages/vitest/src/node/cli/cli-config.ts +++ b/packages/vitest/src/node/cli/cli-config.ts @@ -193,7 +193,7 @@ export const cliOptionsConfig: VitestCLIOptions = { }, reporter: { description: - '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`](https://vitest.dev/config/coverage#coverage-reporter) for more information (default: `["text", "html", "clover", "json"]`)', argument: '', subcommands: null, // don't support custom objects array: true, @@ -485,7 +485,7 @@ export const cliOptionsConfig: VitestCLIOptions = { }, hooks: { description: - 'Changes the order in which hooks are executed. Accepted values are: "stack", "list" and "parallel". Visit [`sequence.hooks`](https://vitest.dev/config/#sequence-hooks) for more information (default: `"parallel"`)', + 'Changes the order in which hooks are executed. Accepted values are: "stack", "list" and "parallel". Visit [`sequence.hooks`](https://vitest.dev/config/sequence#sequence-hooks) for more information (default: `"parallel"`)', argument: '', }, setupFiles: {