···11# Node API
2233::: warning
44-Vitest exposes experimental private API. Breaking changes might not follow semver, please pin Vitest's version when using it.
44+Vitest exposes experimental private API. Breaking changes might not follow SemVer, please pin Vitest's version when using it.
55:::
6677## startVitest
···18181919`startVitest` function returns `Vitest` instance if tests can be started. It returns `undefined`, if one of the following occurs:
20202121-- Vitest didn't find "vite" package (usually installed with Vitest)
2121+- Vitest didn't find the `vite` package (usually installed with Vitest)
2222- If coverage is enabled and run mode is "test", but the coverage package is not installed (`@vitest/coverage-v8` or `@vitest/coverage-istanbul`)
2323- If the environment package is not installed (`jsdom`/`happy-dom`/`@edge-runtime/vm`)
2424
+2-2
docs/advanced/metadata.md
···11# Task Metadata
2233::: warning
44-Vitest exposes experimental private API. Breaking changes might not follow semver, please pin Vitest's version when using it.
44+Vitest exposes experimental private API. Breaking changes might not follow SemVer, please pin Vitest's version when using it.
55:::
6677If 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.
···7171 custom?: string
7272 }
7373}
7474-```7474+```
+1-1
docs/advanced/pool.md
···55555656If you are using a custom pool, you will have to provide test files and their results yourself - you can reference [`vitest.state`](https://github.com/vitest-dev/vitest/blob/feat/custom-pool/packages/vitest/src/node/state.ts) for that (most important are `collectFiles` and `updateTasks`). Vitest uses `startTests` function from `@vitest/runner` package to do that.
57575858-To communicate between different processes, you can create methods object using `createMethodsRPC` from `vitest/node`, and use any form of communication that you prefer. For example, to use websockets with `birpc` you can write something like this:
5858+To communicate between different processes, you can create methods object using `createMethodsRPC` from `vitest/node`, and use any form of communication that you prefer. For example, to use WebSockets with `birpc` you can write something like this:
59596060```ts
6161import { createBirpc } from 'birpc'
+1-1
docs/advanced/runner.md
···106106Snapshot support and some other features depend on the runner. If you don't want to lose it, you can extend your runner from `VitestTestRunner` imported from `vitest/runners`. It also exposes `BenchmarkNodeRunner`, if you want to extend benchmark functionality.
107107:::
108108109109-## Your task function
109109+## Your Task Function
110110111111You can extend Vitest task system with your tasks. A task is an object that is part of a suite. It is automatically added to the current suite with a `suite.task` method:
112112
+2-2
docs/api/expect.md
···1919expect(input).toBe(2) // jest API
2020```
21212222-Technically this example doesn't use [`test`](/api/#test) function, so in the console you will see Nodejs error instead of Vitest output. To learn more about `test`, please read [Test API Reference](/api/).
2222+Technically this example doesn't use [`test`](/api/#test) function, so in the console you will see Node.js error instead of Vitest output. To learn more about `test`, please read [Test API Reference](/api/).
23232424-Also, `expect` can be used statically to access matchers functions, described later, and more.
2424+Also, `expect` can be used statically to access matcher functions, described later, and more.
25252626::: warning
2727`expect` has no effect on testing types, if the expression doesn't have a type error. If you want to use Vitest as [type checker](/guide/testing-types), use [`expectTypeOf`](/api/expect-typeof) or [`assertType`](/api/assert-type).
+1-1
docs/api/index.md
···370370If you want to have access to `TestContext`, use `describe.each` with a single test.
371371372372::: tip
373373-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.
373373+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.
374374:::
375375376376::: warning
+1-1
docs/api/mock.md
···244244245245Accepts a value that will be returned during the next function call. If chained, every consecutive call will return the specified value.
246246247247-When there are no more `mockReturnValueOnce` values to use, mock will fallback to preivously defined implementation if there is one.
247247+When there are no more `mockReturnValueOnce` values to use, mock will fallback to previously defined implementation if there is one.
248248249249```ts
250250const myMockFn = vi
+5-5
docs/api/vi.md
···150150151151- **Type**: `(path: string, factory?: (importOriginal: () => unknown) => unknown) => void`
152152153153-The same as [`vi.mock`](#vi-mock), but it's not hoisted to the top of the file, so you can reference variables in the global file scope. The next [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) of the module will be mocked.
153153+The same as [`vi.mock`](#vi-mock), but it's not hoisted to the top of the file, so you can reference variables in the global file scope. The next [dynamic import](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) of the module will be mocked.
154154155155::: warning
156156This will not mock modules that were imported before this was called. Don't forget that all static imports in ESM are always [hoisted](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import#hoisting), so putting this before static import will not force it to be called before the import:
···333333```
334334335335::: tip
336336-If during a dynamic import another dynamic import is initiated, this method will wait unti all of them are resolved.
336336+If during a dynamic import another dynamic import is initiated, this method will wait until all of them are resolved.
337337338338This method will also wait for the next `setTimeout` tick after the import is resolved so all synchronous operations should be completed by the time it's resolved.
339339:::
···386386387387- **Type:** `<T, K extends keyof T>(object: T, method: K, accessType?: 'get' | 'set') => MockInstance`
388388389389-Creates a spy on a method or getter/setter of an object simillar to [`vi.fn()`](/#vi-fn). It returns a [mock function](/api/mock).
389389+Creates a spy on a method or getter/setter of an object similar to [`vi.fn()`](/#vi-fn). It returns a [mock function](/api/mock).
390390391391```ts
392392let apples = 0
···724724725725If fake timers are enabled, this method simulates a user changing the system clock (will affect date related API like `hrtime`, `performance.now` or `new Date()`) - however, it will not fire any timers. If fake timers are not enabled, this method will only mock `Date.*` calls.
726726727727-Useful if you need to test anything that depends on the current date - for example [luxon](https://github.com/moment/luxon/) calls inside your code.
727727+Useful if you need to test anything that depends on the current date - for example [Luxon](https://github.com/moment/luxon/) calls inside your code.
728728729729```ts
730730const date = new Date(1998, 11, 19)
···749749750750::: tip
751751Since version `0.35.0` `vi.useFakeTimers()` no longer automatically mocks `process.nextTick`.
752752-It can still be mocked by specyfing the option in `toFake` argument: `vi.useFakeTimers({ toFake: ['nextTick'] })`.
752752+It can still be mocked by specifying the option in `toFake` argument: `vi.useFakeTimers({ toFake: ['nextTick'] })`.
753753:::
754754755755### vi.isFakeTimers
+11-11
docs/config/index.md
···6565```
66666767::: warning
6868-`mergeConfig` helper is availabe in Vitest since v0.30.0. You can import it from `vite` directly, if you use lower version.
6868+`mergeConfig` helper is available in Vitest since v0.30.0. You can import it from `vite` directly, if you use lower version.
6969:::
70707171-If your vite config is defined as a function, you can define the config like this:
7171+If your Vite config is defined as a function, you can define the config like this:
7272```ts
7373import { defineConfig, mergeConfig } from 'vitest/config'
7474import viteConfig from './vite.config'
···138138- **Type:** `'inline' | boolean`
139139- **Default:** `'inline'`
140140141141-Inject inline sourcemap to modules.
141141+Inject inline source map to modules.
142142143143#### server.debug
144144···623623624624#### threads<NonProjectOption />
625625626626-Enable multi-threading using [tinypool](https://github.com/tinylibs/tinypool) (a lightweight fork of [Piscina](https://github.com/piscinajs/piscina)). 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 adviced to use `forks` pool instead.
626626+Enable multi-threading using [tinypool](https://github.com/tinylibs/tinypool) (a lightweight fork of [Piscina](https://github.com/piscinajs/piscina)). 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.
627627628628#### forks<NonProjectOption />
629629···959959::: warning
960960Since Vitest 1.0.0-beta, 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).
961961962962-Beware that the global setup is running in a different global scope, so your tests don't have access to variables defined here. Hovewer, since 1.0.0 you can pass down serializable data to tests via `provide` method:
962962+Beware that the global setup is running in a different global scope, so your tests don't have access to variables defined here. However, since 1.0.0 you can pass down serializable data to tests via `provide` method:
963963964964```ts
965965// globalSetup.js
···13831383:::
1384138413851385::: warning
13861386-This is an experimental feature. Breaking changes might not follow semver, please pin Vitest's version when using it.
13861386+This is an experimental feature. Breaking changes might not follow SemVer, please pin Vitest's version when using it.
13871387:::
1388138813891389#### browser.enabled
···13921392- **Default:** `false`
13931393- **CLI:** `--browser`, `--browser.enabled=false`
1394139413951395-Run all tests inside a browser by default. Can be overriden with [`poolMatchGlobs`](/config/#poolmatchglobs) option.
13951395+Run all tests inside a browser by default. Can be overridden with [`poolMatchGlobs`](/config/#poolmatchglobs) option.
1396139613971397#### browser.name
13981398···1878187818791879Stop test execution when given number of tests have failed.
1880188018811881-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 occured.
18811881+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.
1882188218831883### retry
18841884···19151915- **Type**: `(error: Error, frame: ParsedStack) => boolean | void`
19161916- **Version**: Since Vitest 1.0.0-beta.3
1917191719181918-Apply a filtering function to each frame of each stacktrace when handling errors. The first argument, `error`, is an object with the same properties as a standard `Error`, but it is not an actual instance.
19181918+Apply a filtering function to each frame of each stack trace when handling errors. The first argument, `error`, is an object with the same properties as a standard `Error`, but it is not an actual instance.
1919191919201920-Can be useful for filtering out stacktrace frames from third-party libraries.
19201920+Can be useful for filtering out stack trace frames from third-party libraries.
1921192119221922```ts
19231923import type { ParsedStack } from 'vitest'
···19801980- **Type:** `number | Date`
19811981- **Default:** `Date.now()`
1982198219831983-Installs fake timers with the specified unix epoch.
19831983+Installs fake timers with the specified Unix epoch.
1984198419851985#### fakeTimers.toFake
19861986
+6-5
docs/guide/browser.md
···22title: Browser Mode | Guide
33---
4455-# Browser Mode (experimental)
55+# Browser Mode <Badge type="warning">Experimental</Badge>
6677This page provides information about the experimental browser mode feature in the Vitest API, which allows you to run your tests in the browser natively, providing access to browser globals like window and document. This feature is currently under development, and APIs may change in the future.
88···10101111We developed the Vitest browser mode feature to help improve testing workflows and achieve more accurate and reliable test results. This experimental addition to our testing API allows developers to run tests in a native browser environment. In this section, we'll explore the motivations behind this feature and its benefits for testing.
12121313-### Different ways of testing
1313+### Different Ways of Testing
14141515There are different ways to test JavaScript code. Some testing frameworks simulate browser environments in Node.js, while others run tests in real browsers. In this context, [jsdom](https://www.npmjs.com/package/jsdom) is an example of a spec implementation that simulates a browser environment by being used with a test runner like Jest or Vitest, while other testing tools such as [WebdriverIO](https://webdriver.io/) or [Cypress](https://www.cypress.io/) allow developers to test their applications in a real browser or in case of [Playwright](https://playwright.dev/) provide you a browser engine.
16161717-### The simulation caveat
1717+### The Simulation Caveat
18181919Testing JavaScript programs in simulated environments such as jsdom or happy-dom has simplified the test setup and provided an easy-to-use API, making them suitable for many projects and increasing confidence in test results. However, it is crucial to keep in mind that these tools only simulate a browser environment and not an actual browser, which may result in some discrepancies between the simulated environment and the real environment. Therefore, false positives or negatives in test results may occur.
2020···4747})
4848```
49495050-## Browser Option Types:
5050+## Browser Option Types
51515252The browser option in Vitest depends on the provider. Vitest will fail, if you pass `--browser` and don't specify its name in the config file. Available options:
5353···6161 - `webkit`
6262 - `chromium`
63636464-## Cross-browser Testing:
6464+## Cross-Browser Testing
65656666When you specify a browser name in the browser option, Vitest will try to run the specified browser using [WebdriverIO](https://webdriver.io/) by default, and then run the tests there. This feature makes cross-browser testing easy to use and configure in environments like a CI. If you don't want to use WebdriverIO, you can configure the custom browser provider by using `browser.provider` option.
6767···109109In this case, Vitest will run in headless mode using the Chrome browser.
110110111111## Limitations
112112+112113### Thread Blocking Dialogs
113114114115When using Vitest Browser, it's important to note that thread blocking dialogs like `alert` or `confirm` cannot be used natively. This is because they block the web page, which means Vitest cannot continue communicating with the page, causing the execution to hang.
+1-1
docs/guide/cli.md
···8181| `--mode` | Override Vite mode (default: `test`) |
8282| `--mode <name>` | Override Vite mode (default: `test`) |
8383| `--globals` | Inject APIs globally |
8484-| `--dom` | Mock browser api with happy-dom |
8484+| `--dom` | Mock browser API with happy-dom |
8585| `--browser [options]` | Run tests in [the browser](/guide/browser) (default: `false`) |
8686| `--environment <env>` | Runner environment (default: `node`) |
8787| `--passWithNoTests` | Pass when no tests found |
···10101111It is possible to use Jest in Vite setups. [@sodatea](https://twitter.com/haoqunjiang) built [vite-jest](https://github.com/sodatea/vite-jest#readme), which aims to provide first-class Vite integration for [Jest](https://jestjs.io/). The last [blockers in Jest](https://github.com/sodatea/vite-jest/blob/main/packages/vite-jest/README.md#vite-jest) have been solved, so this is a valid option for your unit tests.
12121313-However, in a world where we have [Vite](https://vitejs.dev) providing support for the most common web tooling (typescript, JSX, most popular UI Frameworks), Jest represents a duplication of complexity. If your app is powered by Vite, having two different pipelines to configure and maintain is not justifiable. With Vitest you get to define the configuration for your dev, build and test environments as a single pipeline, sharing the same plugins and the same vite.config.js.
1313+However, in a world where we have [Vite](https://vitejs.dev) providing support for the most common web tooling (TypeScript, JSX, most popular UI Frameworks), Jest represents a duplication of complexity. If your app is powered by Vite, having two different pipelines to configure and maintain is not justifiable. With Vitest you get to define the configuration for your dev, build and test environments as a single pipeline, sharing the same plugins and the same vite.config.js.
14141515-Even if your library is not using Vite (for example, if it is built with esbuild or rollup), Vitest is an interesting option as it gives you a faster run for your unit tests and a jump in DX thanks to the default watch mode using Vite instant Hot Module Reload (HMR). Vitest offers compatibility with most of the Jest API and ecosystem libraries, so in most projects, it should be a drop-in replacement for Jest.
1515+Even if your library is not using Vite (for example, if it is built with esbuild or Rollup), Vitest is an interesting option as it gives you a faster run for your unit tests and a jump in DX thanks to the default watch mode using Vite instant Hot Module Reload (HMR). Vitest offers compatibility with most of the Jest API and ecosystem libraries, so in most projects, it should be a drop-in replacement for Jest.
16161717## Cypress
1818···40404141## Web Test Runner
42424343-[@web/test-runner](https://modern-web.dev/docs/test-runner/overview/) runs tests inside a headless browser, providing the same execution environment as your web application without the need for mocking out browser APIs or the DOM. This also makes it possible to debug inside a real browser using the devtools, although there is no UI shown for stepping through the test, as there is in Cypress tests. There is a watch mode, but it is not as intelligent as that of vitest, and may not always re-run the tests you want. To use @web/test-runner with a vite project, use [@remcovaes/web-test-runner-vite-plugin](https://github.com/remcovaes/web-test-runner-vite-plugin). @web/test-runner does not include assertion or mocking libraries, so it is up to you to add them.
4343+[@web/test-runner](https://modern-web.dev/docs/test-runner/overview/) runs tests inside a headless browser, providing the same execution environment as your web application without the need for mocking out browser APIs or the DOM. This also makes it possible to debug inside a real browser using the devtools, although there is no UI shown for stepping through the test, as there is in Cypress tests.
4444+4545+There is a watch mode, but it is not as intelligent as that of Vitest, and may not always re-run the tests you want.
4646+4747+To use @web/test-runner with a Vite project, use [@remcovaes/web-test-runner-vite-plugin](https://github.com/remcovaes/web-test-runner-vite-plugin). @web/test-runner does not include assertion or mocking libraries, so it is up to you to add them.
44484549## uvu
4646-[uvu](https://github.com/lukeed/uvu) is a test runner for Node.js and the browser. It runs tests in a single thread, so tests are not isolated and can leak across files. Vitest, however, uses worker threads to isolate tests and run them in parallel. For transforming your code, uvu relies on require and loader hooks. Vitest uses [Vite](https://vitejs.dev), so files are transformed with the full power of Vite's plugin system. In a world where we have Vite providing support for the most common web tooling (typescript, JSX, most popular UI Frameworks), uvu represents a duplication of complexity. If your app is powered by Vite, having two different pipelines to configure and maintain is not justifiable. With Vitest you get to define the configuration for your dev, build and test environments as a single pipeline, sharing the same plugins and the same vite.config.js. uvu does not provide an intelligent watch mode to rerun the changed tests, while Vitest gives you amazing DX thanks to the default watch mode using Vite instant Hot Module Reload (HMR). uvu is a fast option for running simple tests, but Vitest can be faster and more reliable for more complex tests and projects.
5050+5151+[uvu](https://github.com/lukeed/uvu) is a test runner for Node.js and the browser. It runs tests in a single thread, so tests are not isolated and can leak across files. Vitest, however, uses worker threads to isolate tests and run them in parallel.
5252+5353+For transforming your code, uvu relies on require and loader hooks. Vitest uses [Vite](https://vitejs.dev), so files are transformed with the full power of Vite's plugin system. In a world where we have Vite providing support for the most common web tooling (TypeScript, JSX, most popular UI Frameworks), uvu represents a duplication of complexity. If your app is powered by Vite, having two different pipelines to configure and maintain is not justifiable. With Vitest you get to define the configuration for your dev, build and test environments as a single pipeline, sharing the same plugins and the same configuration.
5454+5555+uvu does not provide an intelligent watch mode to rerun the changed tests, while Vitest gives you amazing DX thanks to the default watch mode using Vite instant Hot Module Reload (HMR).
5656+5757+uvu is a fast option for running simple tests, but Vitest can be faster and more reliable for more complex tests and projects.
+2-2
docs/guide/coverage.md
···118118119119Please refer to the type definition for more details.
120120121121-## Changing the default coverage folder location
121121+## Changing the Default Coverage Folder Location
122122123123When running a coverage report, a `coverage` folder is created in the root directory of your project. If you want to move it to a different directory, use the `test.coverage.reportsDirectory` property in the `vite.config.js` file.
124124···134134})
135135```
136136137137-## Ignoring code
137137+## Ignoring Code
138138139139Both coverage providers have their own ways how to ignore code from coverage reports:
140140
+7-7
docs/guide/debugging.md
···88When debugging tests you might want to use `--test-timeout` CLI argument to prevent tests from timing out when stopping at breakpoints.
99:::
10101111-## VSCode
1111+## VS Code
12121313-Quick way to debug tests in VSCode is via `JavaScript Debug Terminal`. Open a new `JavaScript Debug Terminal` and run `npm run test` or `vitest` directly. *this works with any code ran in Node, so will work with most JS testing frameworks*
1313+Quick way to debug tests in VS Code is via `JavaScript Debug Terminal`. Open a new `JavaScript Debug Terminal` and run `npm run test` or `vitest` directly. *this works with any code ran in Node, so will work with most JS testing frameworks*
14141515
16161717-You can also add a dedicated launch configuration to debug a test file in VSCode:
1717+You can also add a dedicated launch configuration to debug a test file in VS Code:
18181919```json
2020{
···44444545Setting | Value
4646 --- | ---
4747-Working directory | /path/to/your-project-root
4848-JavaScript file | ./node_modules/vitest/vitest.mjs
4949-Application parameters | run --pool forks
4747+Working directory | `/path/to/your-project-root`
4848+JavaScript file | `./node_modules/vitest/vitest.mjs`
4949+Application parameters | `run --pool forks`
50505151Then run this configuration in debug mode. The IDE will stop at JS/TS breakpoints set in the editor.
5252···6262vitest --inspect-brk --pool forks --poolOptions.forks.singleFork
6363```
64646565-Once Vitest starts it will stop execution and waits for you to open developer tools that can connect to [NodeJS inspector](https://nodejs.org/en/docs/guides/debugging-getting-started/). You can use Chrome DevTools for this by opening `chrome://inspect` on browser.
6565+Once Vitest starts it will stop execution and wait for you to open developer tools that can connect to [Node.js inspector](https://nodejs.org/en/docs/guides/debugging-getting-started/). You can use Chrome DevTools for this by opening `chrome://inspect` on browser.
66666767In watch mode you can keep the debugger open during test re-runs by using the `--poolOptions.threads.isolate false` options.
+5-1
docs/guide/environment.md
···11+---
22+title: Test Environment | Guide
33+---
44+15# Test Environment
2637Vitest provides [`environment`](/config/#environment) option to run code inside a specific environment. You can modify how environment behaves with [`environmentOptions`](/config/#environmentoptions) option.
···913- `happy-dom` emulates browser environment by providing Browser API, and considered to be faster than jsdom, but lacks some API, uses [`happy-dom`](https://github.com/capricorn86/happy-dom) package
1014- `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
11151212-## Environments for specific files
1616+## Environments for Specific Files
13171418When setting `environment` option in your config, it will apply to all the test files in your project. To have more fine-grained control, you can use control comments to specify environment for specific files. Control comments are comments that start with `@vitest-environment` and are followed by the environment name:
1519
+7-7
docs/guide/features.md
···1010<div h-2 />
1111<CourseLink href="https://vueschool.io/lessons/your-first-test?friend=vueuse">Learn how to write your first test by Video</CourseLink>
12121313-## Shared config between test, dev and build
1313+## Shared Config between Test, Dev and Build
14141515Vite's config, transformers, resolvers, and plugins. Use the same setup from your app to run the tests.
1616···26262727`vitest` starts in `watch mode` **by default in development environment** and `run mode` in CI environment (when `process.env.CI` presents) smartly. You can use `vitest watch` or `vitest run` to explicitly specify the desired mode.
28282929-## Common web idioms out-of-the-box
2929+## Common Web Idioms Out-Of-The-Box
30303131Out-of-the-box ES Module / TypeScript / JSX support / PostCSS
3232···42424343Learn more about [Test Filtering](./filtering.md).
44444545-## Running tests concurrently
4545+## Running Tests Concurrently
46464747Use `.concurrent` in consecutive tests to run them in parallel.
4848···91919292Learn more at [Snapshot](/guide/snapshot).
93939494-## Chai and Jest `expect` compatibility
9494+## Chai and Jest `expect` Compatibility
95959696[Chai](https://www.chaijs.com/) is built-in for assertions plus [Jest `expect`](https://jestjs.io/docs/expect)-compatible APIs.
9797···156156157157Learn more at [Coverage](/guide/coverage).
158158159159-## In-source testing
159159+## In-Source Testing
160160161161Vitest also provides a way to run tests within your source code along with the implementation, similar to [Rust's module tests](https://doc.rust-lang.org/book/ch11-03-test-organization.html#the-tests-module-and-cfgtest).
162162···183183184184Learn more at [In-source testing](/guide/in-source).
185185186186-## Benchmarking <sup><code>experimental</code></sup>
186186+## Benchmarking <Badge type="warning">Experimental</Badge>
187187188188Since Vitest 0.23.0, you can run benchmark tests with [`bench`](/api/#bench)
189189function via [Tinybench](https://github.com/tinylibs/tinybench) to compare performance results.
···208208})
209209```
210210211211-## Type Testing <sup><code>experimental</code></sup>
211211+## Type Testing <Badge type="warning">Experimental</Badge>
212212213213Since Vitest 0.25.0 you can [write tests](/guide/testing-types) to catch type regressions. Vitest comes with [`expect-type`](https://github.com/mmkal/expect-type) package to provide you with a similar and easy to understand API.
214214
+2-2
docs/guide/ide.md
···4455# IDE Integrations
6677-## VS Code <sup><code>Official</code></sup>
77+## VS Code <Badge>Offical</Badge>
8899<p text-center>
1010<img src="https://raw.githubusercontent.com/vitest-dev/vscode/main/img/cover.png" w-60>
···26262727
28282929-## Wallaby.js <sup><code>Paid (free for OSS)</code></sup>
2929+## Wallaby.js <Badge>Paid (free for OSS)</Badge>
30303131Created by [The Wallaby Team](https://wallabyjs.com)
3232
+5-5
docs/guide/in-source.md
···11---
22-title: In-source testing | Guide
22+title: In-Source Testing | Guide
33---
4455-# In-source testing
55+# In-Source Testing
6677Vitest also provides a way to run tests within your source code along side the implementation, similar to [Rust's module tests](https://doc.rust-lang.org/book/ch11-03-test-organization.html#the-tests-module-and-cfgtest).
88···5151$ npx vitest
5252```
53535454-## Production build
5454+## Production Build
55555656For the production build, you will need to set the `define` options in your config file, letting the bundler do the dead code elimination. For example, in Vite
5757···9292</details>
93939494<details my2>
9595-<summary text-xl>rollup</summary>
9595+<summary text-xl>Rollup</summary>
96969797```ts
9898// rollup.config.js
···108108}
109109```
110110111111-Learn more: <a href="https://rollupjs.org/" target="_blank">rollup</a>
111111+Learn more: <a href="https://rollupjs.org/" target="_blank">Rollup</a>
112112113113</details>
114114
+1-1
docs/guide/index.md
···14141515You can try Vitest online on [StackBlitz](https://vitest.new). It runs Vitest directly in the browser, and it is almost identical to the local setup but doesn't require installing anything on your machine.
16161717-## Adding Vitest to your Project
1717+## Adding Vitest to Your Project
18181919<CourseLink href="https://vueschool.io/lessons/how-to-install-vitest?friend=vueuse">Learn how to install by Video</CourseLink>
2020
+3-3
docs/guide/migration.md
···14141515If 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).
16161717-### Module mocks
1717+### Module Mocks
18181919When mocking a module in Jest, the factory argument's return value is the default export. In Vitest, the factory argument has to return an object with each export explicitly defined. For example, the following `jest.mock` would have to be updated as follows:
2020···31313232Unlike Jest, mocked modules in `<root>/__mocks__` are not loaded unless `vi.mock()` is called. If you need them to be mocked in every test, like in Jest, you can mock them inside [`setupFiles`](/config/#setupfiles).
33333434-### Importing the original of a mocked package
3434+### Importing the Original of a Mocked Package
35353636If you are only partially mocking a package, you might have previously used Jest's function `requireActual`. In Vitest, you should replace these calls with `vi.importActual`.
3737···46464747### Replace property
48484949-If you want to modify the object, you will use [replaceProperty API](https://jestjs.io/docs/jest-object#jestreplacepropertyobject-propertykey-value) in Jest, you can use [`vi.stubEnv`](https://vitest.dev/api/vi.html#vi-stubenv) or [`vi.spyOn`](/api/vi#vi-spyon) to do the same also in Vitest.
4949+If you want to modify the object, you will use [replaceProperty API](https://jestjs.io/docs/jest-object#jestreplacepropertyobject-propertykey-value) in Jest, you can use [`vi.stubEnv`](https://vitest.dev/api/vi.html#vi-stubenv) or [`vi.spyOn`](/api/vi#vi-spyon) to do the same also in Vitest.
50505151### Done Callback
5252
+3-3
docs/guide/mocking.md
···156156157157Mock modules observe third-party-libraries, that are invoked in some other code, allowing you to test arguments, output or even redeclare its implementation.
158158159159-See the [`vi.mock()` api section](/api/vi#vi-mock) for a more in-depth detailed API description.
159159+See the [`vi.mock()` API section](/api/vi#vi-mock) for a more in-depth detailed API description.
160160161161-### Automocking algorithm
161161+### Automocking Algorithm
162162163163If your code is importing a mocked module, without any associated `__mocks__` file or `factory` for this module, Vitest will mock the module itself by invoking it and mocking every export.
164164···330330331331When we test code that involves timeouts or intervals, instead of having our tests wait it out or timeout, we can speed up our tests by using "fake" timers that mock calls to `setTimeout` and `setInterval`.
332332333333-See the [`vi.useFakeTimers` api section](/api/vi#vi-usefaketimers) for a more in depth detailed API description.
333333+See the [`vi.useFakeTimers` API section](/api/vi#vi-usefaketimers) for a more in depth detailed API description.
334334335335### Example
336336
+19-19
docs/guide/reporters.md
···5566# Reporters
7788-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](https://vitest.dev/config/#reporters). If no reporter is specified, Vitest will use the `default` reporter as described below.
88+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.
991010Using reporters via command line:
1111···28282929## Reporter Output
30303131-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](https://vitest.dev/config/#outputfile) either in your Vite configuration file or via CLI.
3131+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.
32323333:::code-group
3434```bash [CLI]
···80808181## Built-in Reporters
82828383-### Default reporter
8383+### Default Reporter
84848585By default (i.e. if no reporter is specified), Vitest will display results for each test suite hierarchically as they run, and then collapse after a suite passes. When all tests have finished running, the final terminal output will display a summary of results and details of any failed tests.
8686···106106 Duration 1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)
107107```
108108109109-### Basic reporter
109109+### Basic Reporter
110110111111-The `basic` reporter displays the test files that have run and a summary of results after the entire suite has finished running. Individual tests are not included in the report unless they fail.
111111+The `basic` reporter displays the test files that have run and a summary of results after the entire suite has finished running. Individual tests are not included in the report unless they fail.
112112113113:::code-group
114114```bash [CLI]
···135135 Duration 1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)
136136```
137137138138-### Verbose reporter
138138+### Verbose Reporter
139139140140Follows the same hierarchical structure as the `default` reporter, but does not collapse sub-trees for passed test suites. The final terminal output displays all tests that have run, including those that have passed.
141141···171171 Duration 1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)
172172```
173173174174-### Dot reporter
174174+### Dot Reporter
175175176176Prints a single dot for each completed test to provide minimal output while still showing all tests that have run. Details are only provided for failed tests, along with the `basic` reporter summary for the suite.
177177···200200 Duration 1.26s (transform 35ms, setup 1ms, collect 90ms, tests 1.47s, environment 0ms, prepare 267ms)
201201```
202202203203-### JUnit reporter
203203+### JUnit Reporter
204204205205-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`](##Reporter-Output) configuration option.
205205+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.
206206207207:::code-group
208208```bash [CLI]
···236236```
237237The outputted XML contains nested `testsuites` and `testcase` tags. You can use the environment variables `VITEST_JUNIT_SUITE_NAME` and `VITEST_JUNIT_CLASSNAME` to configure their `name` and `classname` attributes, respectively.
238238239239-### JSON reporter
239239+### JSON Reporter
240240241241-Outputs a report of the test results in JSON format. Can either be printed to the terminal or written to a file using the [`outputFile`](##Reporter-Output) configuration option.
241241+Outputs a report of the test results in JSON format. Can either be printed to the terminal or written to a file using the [`outputFile`](/config/#outputfile) configuration option.
242242243243:::code-group
244244```bash [CLI]
···300300}
301301```
302302303303-### HTML reporter
303303+### HTML Reporter
304304305305Generates 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.
306306307307-Output file can be specified using the [`outputFile`](##Reporter-Output) configuration option. If no `outputFile` option is provided, a new HTML file will be created.
307307+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.
308308309309:::code-group
310310```bash [CLI]
···324324This reporter requires installed [`@vitest/ui`](/guide/ui) package.
325325:::
326326327327-### TAP reporter
327327+### TAP Reporter
328328329329-Outputs a report following [Test Anything Protocol](https://testanything.org/) (TAP).
329329+Outputs a report following [Test Anything Protocol](https://testanything.org/) (TAP).
330330331331:::code-group
332332```bash [CLI]
···364364}
365365```
366366367367-### TAP flat reporter
367367+### TAP Flat Reporter
368368369369Outputs a TAP flat report. Like the `tap` reporter, test results are formatted to follow TAP standards, but test suites are formatted as a flat list rather than a nested hierarchy.
370370···399399```
400400401401402402-### Hanging process reporter
402402+### Hanging Process Reporter
403403404404Displays a list of hanging processes, if any are preventing Vitest from exiting safely. The `hanging-process` reporter does not itself display test results, but can be used in conjunction with another reporter to monitor processes while tests run. Using this reporter can be resource-intensive, so should generally be reserved for debugging purposes in situations where Vitest consistently cannot exit the process.
405405···417417```
418418:::
419419420420-## Custom reporters
420420+## Custom Reporters
421421422422You can use third-party custom reporters installed from NPM by specifying their package name in the reporters' option:
423423···441441npx vitest --reporter=./path/to/reporter.ts
442442```
443443444444-Custom reporters should implement the [Reporter interface](https://github.com/vitest-dev/vitest/blob/main/packages/vitest/src/types/reporter.ts).
444444+Custom reporters should implement the [Reporter interface](https://github.com/vitest-dev/vitest/blob/main/packages/vitest/src/types/reporter.ts).
+2-2
docs/guide/testing-types.md
···63636464The `This expression is not callable` part isn't all that helpful - the meaningful error is the next line, `Type 'ExpectString<number> has no call signatures`. This essentially means you passed a number but asserted it should be a string.
65656666-If TypeScript added support for ["throw" types](https://github.com/microsoft/TypeScript/pull/40468) these error messagess could be improved significantly. Until then they will take a certain amount of squinting.
6666+If TypeScript added support for ["throw" types](https://github.com/microsoft/TypeScript/pull/40468) these error messages could be improved significantly. Until then they will take a certain amount of squinting.
67676868#### Concrete "expected" objects vs typeargs
6969···109109```
110110:::
111111112112-## Run typechecking
112112+## Run Typechecking
113113114114Since Vitest 1.0, to enabled typechecking, just add [`--typecheck`](/config/#typecheck) flag to your Vitest command in `package.json`:
115115
+1-1
docs/guide/ui.md
···4141:::
42424343::: tip
4444-To preview your HTML report, you can use [vite preview](https://vitejs.dev/guide/cli.html#vite-preview) command:
4444+To preview your HTML report, you can use the [vite preview](https://vitejs.dev/guide/cli.html#vite-preview) command:
45454646```sh
4747npx vite preview --outDir ./html
+1-1
docs/guide/why.md
···88This guide assumes that you are familiar with Vite. A good way to start learning more is to read the [Why Vite Guide](https://vitejs.dev/guide/why.html), and [Next generation frontend tooling with ViteJS](https://www.youtube.com/watch?v=UJypSr8IhKY), a stream where [Evan You](https://twitter.com/youyuxi) did a demo explaining the main concepts.
99:::
10101111-## The need for a Vite native test runner
1111+## The Need for a Vite Native Test Runner
12121313Vite's out-of-the-box support for common web patterns, features like glob imports and SSR primitives, and its many plugins and integrations are fostering a vibrant ecosystem. Its dev and build story are key to its success. For docs, there are several SSG-based alternatives powered by Vite. Vite's Unit Testing story hasn't been clear though. Existing options like [Jest](https://jestjs.io/) were created in a different context. There is a lot of duplication between Jest and Vite, forcing users to configure two different pipelines.
1414
+6-2
docs/guide/workspace.md
···11+---
22+title: Workspace | Guide
33+---
44+15# Workspace
2633-Vitest provides built-in support for monorepositories through a workspace configuration file. You can create a workspace to define your project's setups.
77+Vitest provides built-in support for monorepos through a workspace configuration file. You can create a workspace to define your project's setups.
4855-## Defining a workspace
99+## Defining a Workspace
610711A workspace should have a `vitest.workspace` or `vitest.projects` file in its root (in the same folder as your config file if you have one). Vitest supports `ts`/`js`/`json` extensions for this file.
812
+1-1
packages/browser/README.md
···2233Browser runner for Vitest.
4455-> ⚠️ This package is **experimental**. While this package will be released along with other packages, it will not follow semver for breaking changes until we mark it as ready.
55+> ⚠️ This package is **experimental**. While this package will be released along with other packages, it will not follow SemVer for breaking changes until we mark it as ready.
6677## Progress
88
+2-2
packages/vitest/src/node/cli.ts
···2929 .option('--run', 'Disable watch mode')
3030 .option('--mode <name>', 'Override Vite mode (default: test)')
3131 .option('--globals', 'Inject apis globally')
3232- .option('--dom', 'Mock browser api with happy-dom')
3232+ .option('--dom', 'Mock browser API with happy-dom')
3333 .option('--browser [options]', 'Run tests in the browser (default: false)')
3434 .option('--pool <pool>', 'Specify pool, if not running in the browser (default: threads)')
3535 .option('--poolOptions <options>', 'Specify pool options')
···134134}
135135136136async function benchmark(cliFilters: string[], options: CliOptions): Promise<void> {
137137- console.warn(c.yellow('Benchmarking is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest\'s version when using it.'))
137137+ console.warn(c.yellow('Benchmarking is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest\'s version when using it.'))
138138 await start('benchmark', cliFilters, options)
139139}
140140
+1-1
packages/vitest/src/node/config.ts
···398398 resolved.typecheck.enabled ??= false
399399400400 if (resolved.typecheck.enabled)
401401- console.warn(c.yellow('Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow semver, please pin Vitest\'s version when using it.'))
401401+ console.warn(c.yellow('Testing types with tsc and vue-tsc is an experimental feature.\nBreaking changes might not follow SemVer, please pin Vitest\'s version when using it.'))
402402403403 resolved.browser ??= {} as any
404404 resolved.browser.enabled ??= false
···89899090exports[`should fail > typechecks empty "include" but with tests 1`] = `
9191"Testing types with tsc and vue-tsc is an experimental feature.
9292-Breaking changes might not follow semver, please pin Vitest's version when using it.
9292+Breaking changes might not follow SemVer, please pin Vitest's version when using it.
93939494⎯⎯⎯⎯⎯⎯ Typecheck Error ⎯⎯⎯⎯⎯⎯⎯
9595Error: error TS18003: No inputs were found in config file '<root>/tsconfig.vitest-temp.json'. Specified 'include' paths were '["src"]' and 'exclude' paths were '["**/dist/**"]'.