Registry / testing / vitest

vitest

JSON →
library2.0jsnpmunverified

Vitest is a next-generation testing framework tightly integrated with Vite, offering a fast, Jest-compatible API for unit and component testing. As of version 4.1.4, it leverages Vite's blazing-fast HMR and shared configuration, making it an excellent choice for modern web projects. It features out-of-the-box support for TypeScript, JSX, and Vue/React components, along with advanced capabilities like in-source testing, snapshot testing, mocking, and parallel test execution. The project maintains an active release cadence, frequently pushing minor updates and experimental features, ensuring it stays current with ecosystem changes and user needs. Key differentiators include its speed, seamless Vite integration, and a rich ecosystem of plugins for coverage (V8, Istanbul), UI, and browser testing environments like JSDOM and Happy DOM.

npm install vitest
INSTALL
IMPORT
SIG · VITEST
V
vitest
testingjavascriptv2.0
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

test
import { test, expect } from 'vitest'
const { test, expect } = require('vitest')
Vitest is primarily an ESM-first framework. While CommonJS is supported via `require()`, named imports are the standard and recommended approach.
vi
import { vi } from 'vitest'
const { vi } = require('vitest')
The `vi` global provides Jest-compatible mocking utilities like `vi.mock`, `vi.fn`, and `vi.spyOn`. It's exposed globally during tests, but importing it explicitly is good practice for type safety and clarity.
defineConfig
import { defineConfig } from 'vitest/config'
import { defineConfig } from 'vitest'
Configuration helpers like `defineConfig` are imported from `vitest/config`, not the main `vitest` package.

This quickstart demonstrates basic Vitest setup with `defineConfig`, writing tests with `describe`, `it`, and `expect`, performing module mocking with `vi.mock`, and creating snapshots.

import { defineConfig } from 'vitest/config'; import { describe, it, expect, vi } from 'vitest'; // vitest.config.ts export default defineConfig({ test: { environment: 'jsdom', // or 'node', 'happy-dom' globals: true, setupFiles: ['./vitest.setup.ts'], }, }); // vitest.setup.ts (optional) // This file runs before all tests console.log('Vitest setup running...'); // my-utils.ts export const sum = (a: number, b: number) => a + b; export const fetchData = async () => { // In a real app, this would fetch data return Promise.resolve({ data: 'Hello Vitest' }); }; // my-utils.test.ts describe('my-utils', () => { it('sums two numbers', () => { expect(sum(1, 2)).toBe(3); }); it('fetches data correctly', async () => { // Mock fetchData to avoid actual network requests vi.spyOn(global, 'fetch').mockResolvedValue({ json: () => Promise.resolve({ data: 'Mocked Data' }) } as any); const result = await fetchData(); expect(result).toEqual({ data: 'Hello Vitest' }); // Note: Still testing fetchData's *internal* mock of fetch, not the actual global fetch. expect(vi.spyOn(global, 'fetch')).toHaveBeenCalledTimes(0); // My specific example of fetchData doesn't use global.fetch directly. // If fetchData *did* use global.fetch, the above spyOn would work. // For this specific example, let's mock the module itself for simplicity. vi.restoreAllMocks(); const mockFetch = vi.fn().mockResolvedValue({ data: 'Mocked Data' }); vi.mock('./my-utils', () => ({ fetchData: mockFetch })); const { fetchData: mockedFetchData } = await import('./my-utils'); const data = await mockedFetchData(); expect(data).toEqual({ data: 'Mocked Data' }); expect(mockFetch).toHaveBeenCalled(); }); it('creates snapshots', () => { const user = { id: 1, name: 'Vitest User' }; expect(user).toMatchSnapshot(); }); });
vitest --version
Debug
Known issues
breakingVitest version 4.x officially requires Node.js v20 or higher. Earlier Node.js versions are not supported.
fix
Upgrade your Node.js environment to version 20, 22, or 24 LTS or newer using tools like `nvm` or your preferred package manager.
affects: >=4.0.0
gotchaVitest's default environment is Node. If you are testing browser-specific code (e.g., DOM manipulation), you need to explicitly configure a browser environment like JSDOM or Happy DOM.
fix
Add `environment: 'jsdom'` or `environment: 'happy-dom'` to your `vitest.config.ts` or `vite.config.ts` under the `test` option. Remember to install the respective peer dependency (`jsdom` or `happy-dom`).
affects: >=1.0.0
breakingA CVE related to the `flatted` dependency (CVE-2023-40618) affected earlier versions of Vitest, potentially leading to prototype pollution vulnerabilities.
fix
Upgrade Vitest to version 4.1.2 or higher to ensure the `flatted` dependency is updated to a patched version, mitigating the CVE.
affects: <4.1.2
gotchaStarting with Vitest v4.1.2, `setupFiles` are no longer resolved from parent directories, affecting monorepo setups or complex project structures where setup files were implicitly picked up.
fix
Explicitly specify the full or relative path to your `setupFiles` in `vitest.config.ts` or `vite.config.ts` to ensure they are correctly located and executed.
affects: >=4.1.2
gotchaWhen using `vi.mock` for module mocking, ensure that the module being mocked is imported *after* the `vi.mock` call, especially for hoisted mocks, to guarantee the mock is applied correctly. ESM module loading order can be tricky.
fix
Place your `vi.mock('module-name', () => ({ ... }))` calls at the top of your test file, before any `import` statements for the module you are mocking. For hoisted mocks (`vi.hoisted`), follow its specific usage pattern carefully.
affects: >=1.0.0
Errors
Common errors & fixes
ReferenceError: test is not defined
The `test` global is not available, often due to not configuring `globals: true` or incorrect import.
fix
In your `vitest.config.ts`, ensure `test: { globals: true }` is set, or explicitly import `test` and `expect` from `vitest`: `import { test, expect } from 'vitest';`
Error: Failed to load url /@fs/path/to/my/module.ts (reason: Module not found)
Vitest (via Vite) cannot resolve a module path, often related to `tsconfig.json` paths or Vite aliases not being correctly configured for the test environment.
fix
Check your `tsconfig.json` `paths` and `vite.config.ts` `resolve.alias` configurations. Ensure they are correctly pointing to your source files and that Vitest is picking up the correct configuration. Sometimes a `clearCache` or rebuilding helps.
TypeError: (0 , import_vitest.vi) is not a function
This usually indicates a CommonJS (`require`) context trying to use an ESM export, or a module resolution issue where `vi` is not correctly imported.
fix
Ensure you are using `import { vi } from 'vitest'` in ESM files. If you are in a CommonJS environment, check your Node.js configuration for ESM compatibility or ensure Vitest is correctly transpiling/handling module types.
Cannot read properties of undefined (reading 'document')
You are running browser-specific code without a DOM environment configured. The default Vitest environment is 'node'.
fix
Set `environment: 'jsdom'` or `environment: 'happy-dom'` in your `vitest.config.ts` under the `test` option. Remember to install `jsdom` or `happy-dom` as a peer dependency.
Upgrade
Version history
2.0latest on npm
Audit
Dependencies
viterequiredVitest is powered by Vite and requires a compatible version for core functionality and configuration.
jsdomoptionalProvides a browser-like DOM environment for testing web components or browser-specific logic. Alternatively, 'happy-dom' can be used.
happy-domoptionalAn alternative, potentially faster, browser-like DOM environment for testing web components or browser-specific logic. Can be used instead of 'jsdom'.
@vitest/uioptionalOptional package to enable the Vitest UI, providing an interactive dashboard for test results.
@vitest/coverage-v8optionalOptional package for generating code coverage reports using the V8 engine. Alternatively, '@vitest/coverage-istanbul' can be used.
@types/nodeoptionalRequired for Node.js type definitions when working with Vitest in a TypeScript project, especially for Node.js APIs.
Agent activity
10 hits · last 30 days
node
8
Amazon
1
Resources