Skip to content

Latest commit

 

History

History
514 lines (336 loc) · 13.6 KB

index.md

File metadata and controls

514 lines (336 loc) · 13.6 KB
outline
deep

Configuring Vitest

Configuration

vitest will read your root vite.config.ts when it is present to match with the plugins and setup as your Vite app. If you want to have a different configuration for testing or your main app doesn't rely on Vite specifically, you could either:

  • Create vitest.config.ts, which will have the higher priority and will override the configuration from vite.config.ts
  • Pass --config option to CLI, e.g. vitest --config ./path/to/vitest.config.ts
  • Use process.env.VITEST or mode property on defineConfig (will be set to test if not overridden) to conditionally apply different configuration in vite.config.ts

To configure vitest itself, add test property in your Vite config. You'll also need to add a reference to Vitest types using a triple slash command at the top of your config file, if you are importing defineConfig from vite itself.

using defineConfig from vite you should follow this:

/// <reference types="vitest" />
import { defineConfig } from 'vite'

export default defineConfig({
  test: {
    // ...
  },
})

using defineConfig from vitest/config you should follow this:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    // ...
  },
})

You can retrieve Vitest's default options to expand them if needed:

import { configDefaults, defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    exclude: [...configDefaults.exclude, 'packages/template/*'],
  },
})

Options

include

  • Type: string[]
  • Default: ['**/*.{test,spec}.{js,mjs,cjs,ts,mts,cts,jsx,tsx}']

Files to include in the test run, using glob pattern.

exclude

  • Type: string[]
  • Default: ['**/node_modules/**', '**/dist/**', '**/cypress/**', '**/.{idea,git,cache,output,temp}/**']

Files to exclude from the test run, using glob pattern.

deps

  • Type: { external?, inline? }

Handling for dependencies inlining or externalizing

deps.external

  • Type: (string | RegExp)[]
  • Default: ['**\/node_modules\/**','**\/dist\/**']

Externalize means that Vite will bypass the package to native Node. Externalized dependencies will not be applied Vite's transformers and resolvers, so they do not support HMR on reload. Typically, packages under node_modules are externalized.

deps.inline

  • Type: (string | RegExp)[]
  • Default: []

Vite will process inlined modules. This could be helpful to handle packages that ship .js in ESM format (that Node can't handle).

deps.fallbackCJS

  • Type boolean
  • Default: false

When a dependency is a valid ESM package, try to guess the cjs version based on the path. This might be helpful, if a dependency has the wrong ESM file.

This might potentially cause some misalignment if a package has different logic in ESM and CJS mode.

deps.interopDefault

  • Type: boolean
  • Default: true

Interpret CJS module's default as named exports.

globals

  • Type: boolean
  • Default: false

By default, vitest does not provide global APIs for explicitness. If you prefer to use the APIs globally like Jest, you can pass the --globals option to CLI or add globals: true in the config.

// vite.config.ts
import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    globals: true,
  },
})

To get TypeScript working with the global APIs, add vitest/globals to the types filed in your tsconfig.json

// tsconfig.json
{
  "compilerOptions": {
    "types": ["vitest/globals"]
  }
}

If you are already using unplugin-auto-import in your project, you can also use it directly for auto importing those APIs.

// vite.config.ts
import { defineConfig } from 'vitest/config'
import AutoImport from 'unplugin-auto-import/vite'

export default defineConfig({
  plugins: [
    AutoImport({
      imports: ['vitest'],
      dts: true, // generate TypeScript declaration
    }),
  ],
})

environment

  • Type: 'node' | 'jsdom' | 'happy-dom'
  • Default: 'node'

The environment that will be used for testing. The default environment in Vitest is a Node.js environment. If you are building a web application, you can use browser-like environment through either jsdom or happy-dom instead.

By adding a @vitest-environment docblock or comment at the top of the file, you can specify another environment to be used for all tests in that file:

Docblock style:

/**
 * @vitest-environment jsdom
 */

test('use jsdom in this test file', () => {
  const element = document.createElement('div')
  expect(element).not.toBeNull()
})

Comment style:

// @vitest-environment happy-dom

test('use happy-dom in this test file', () => {
  const element = document.createElement('div')
  expect(element).not.toBeNull()
})

For compatibility with Jest, there is also a @jest-environment:

/**
 * @jest-environment jsdom
 */

test('use jsdom in this test file', () => {
  const element = document.createElement('div')
  expect(element).not.toBeNull()
})

If you are running Vitest with --no-threads flag, your tests will be run in this order: node, jsdom, happy-dom. Meaning, that every test with the same environment is grouped together, but is still run sequentially.

update

  • Type: boolean
  • Default: false

Update snapshot files. This will update all changed snapshots and delete obsolete ones.

watch

  • Type: boolean
  • Default: true

Enable watch mode

root

  • Type: string

Project root

reporters

  • Type: Reporter | Reporter[]
  • Default: 'default'

Custom reporters for output. Reporters can be a Reporter instance or a string to select built in reporters:

  • 'default' - collapse suites when they pass
  • 'verbose' - keep the full task tree visible
  • 'dot' - show each task as a single dot
  • 'junit' - JUnit XML reporter
  • 'json' - give a simple JSON summary
  • path of a custom reporter (e.g. './path/to/reporter.ts', '@scope/reporter')

outputFile

  • Type: string | Record<string, string>

Write test results to a file when the --reporter=json or --reporter=junit option is also specified. By providing an object instead of a string you can define individual outputs when using multiple reporters.

threads

  • Type: boolean
  • Default: true

Enable multi-threading using tinypool (a lightweight fork of Piscina)

:::warning This option is different from Jest's --runInBand. Vitest uses workers not only for running tests in parallel, but also to provide isolation. By disabling this option, your tests will run sequentially, but in the same global context, so you must provide isolation yourself.

This might cause all sorts of issues, if you are relying on global state (frontend frameworks usually do) or your code relies on environment to be defined separately for each test (like, @vue/test-utils). But can be a speed boost for Node tests (up to 3 times faster), that don't necessarily rely on global state or can easily bypass that. :::

maxThreads

  • Type: number
  • Default: available CPUs

Maximum number of threads. You can also use VITEST_MAX_THREADS environment variable.

minThreads

  • Type: number
  • Default: available CPUs

Minimum number of threads. You can also use VITEST_MIN_THREADS environment variable.

testTimeout

  • Type: number
  • Default: 5000

Default timeout of a test in milliseconds

hookTimeout

  • Type: number
  • Default: 10000

Default timeout of a hook in milliseconds

silent

  • Type: boolean
  • Default: false

Silent console output from tests

setupFiles

  • Type: string | string[]

Path to setup files. They will be run before each test file.

You can use process.env.VITEST_WORKER_ID (integer-like string) inside to distinguish between threads (will always be 1, if run with threads: false).

:::tip Note, that if you are running --no-threads, this file will be run in the same global scope. Meaning, that you are accessing the same global object before each test, so make sure you are not doing the same thing more than you need.

For example, you may rely on a global variable:

import { config } from '@some-testing-lib'

if (!globalThis.defined) {
  config.plugins = [myCoolPlugin]
  computeHeavyThing()
  afterEach(() => {
    cleanup()
  })
  globalThis.defined = true
}

globalThis.resetBeforeEachTest = true

:::

globalSetup

  • Type: string | string[]

Path to global setup files, relative to project root

A global setup file can either export named functions setup and teardown or a default function that returns a teardown function (example).

::: info Multiple globalSetup files are possible. setup and teardown are executed sequentially with teardown in reverse order. :::

::: warning Beware that the global setup is run in a different global scope if you are using --threads (default option). If you disabled --threads, everything is run in the same scope (including the Vite server and its plugins). :::

watchExclude

  • Type: string[]
  • Default: ['**/node_modules/**', '**/dist/**']

Glob pattern of file paths to be ignored from triggering watch rerun.

forceRerunTriggers

  • Type: string[]
  • Default: []

Glob patter of file paths that will trigger the whole suite rerun.

Useful if you are testing calling CLI commands, because Vite cannot construct a module graph:

test('execute a script', async () => {
  // Vite cannot rerun this test, if content of `dist/index.js` changes
  await execa('node', ['dist/index.js'])
})

::: tip Make sure that your files are not excluded by watchExclude. :::

isolate

  • Type: boolean
  • Default: true

Isolate environment for each test file. Does not work if you disable --threads.

coverage

  • Type: C8Options
  • Default: undefined

Coverage options passed to C8.

testNamePattern

  • Type string | RegExp

Run tests with full names matching the pattern. If you add OnlyRunThis to this property, tests not containing the word OnlyRunThis in the test name will be skipped.

import { expect, test } from 'vitest'

// run
test('OnlyRunThis', () => {
  expect(true).toBe(true)
})

// skipped
test('doNotRun', () => {
  expect(true).toBe(true)
})

open

  • Type: boolean
  • Default: false

Open Vitest UI (WIP)

api

  • Type: boolean | number
  • Default: false

Listen to port and serve API. When set to true, the default port is 51204

clearMocks

  • Type: boolean
  • Default: false

Will call .mockClear() on all spies before each test. This will clear mock history, but not reset its implementation to the default one.

mockReset

  • Type: boolean
  • Default: false

Will call .mockReset() on all spies before each test. This will clear mock history and reset its implementation to an empty function (will return undefined).

restoreMocks

  • Type: boolean
  • Default: false

Will call .mockRestore() on all spies before each test. This will clear mock history and reset its implementation to the original one.

transformMode

  • Type: { web?, ssr? }

Determine the transform method of modules

transformMode.ssr

  • Type: RegExp[]
  • Default: [/\.([cm]?[jt]sx?|json)$/]

Use SSR transform pipeline for the specified files.
Vite plugins will receive ssr: true flag when processing those files.

transformMode.web

  • Type: RegExp[]
  • Default: modules other than those specified in transformMode.ssr

First do a normal transform pipeline (targeting browser), then then do a SSR rewrite to run the code in Node.
Vite plugins will receive ssr: false flag when processing those files.

When you use JSX as component models other than React (e.g. Vue JSX or SolidJS), you might want to config as following to make .tsx / .jsx transformed as client-side components:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    transformMode: {
      web: [/\.[jt]sx$/],
    },
  },
})

snapshotFormat

  • Type: PrettyFormatOptions

Format options for snapshot testing. These options are passed down to pretty-format.

resolveSnapshotPath

  • Type: (testPath: string, snapExtension: string) => string
  • Default: stores snapshot files in __snapshots__ directory

Overrides default snapshot path. For example, to store snapshots next to test files:

import { defineConfig } from 'vitest/config'

export default defineConfig({
  test: {
    resolveSnapshotPath: (testPath, snapExtension) => testPath + snapExtension,
  },
})

allowOnly

  • Type: boolean
  • Default: false

Allow tests and suites that are marked as only.

passWithNoTests

  • Type: boolean
  • Default: false

Vitest will not fail, if no tests will be found.

logHeapUsage

  • Type: boolean
  • Default: false

Show heap usage after each test. Useful for debugging memory leaks.