Vitest

website·Indexed 42 days ago

https://vitest.dev

A Vite-native testing framework. This documentation covers configuration options including test environment setup, coverage providers, pool management (threads, forks, vmThreads, vmForks), global setup, and integration with Vite config files.

Tokens
197K
Snippets
1.2K
Records
1.4K
Agent score
96%

What's inside Vitest

  1. Overview of Vitest Interactivity API

    The Interactivity API allows developers to simulate user actions (clicks, typing, scrolling) in a browser environment. Unlike traditional event faking, Vitest uses the Chrome DevTools Protocol or WebDriver, making interactions more consistent with actual user behavior. Most userEvent methods can be called either via the userEvent object or directly on a Locator object.
    import { userEvent } from 'vitest/browser'
    
    await userEvent.click(document.querySelector('.button'))
  2. Overview of the Vitest Test Run Lifecycle

    A Vitest test run proceeds through several distinct phases. Phases 4 through 6 (Test File Collection, Execution, and Reporting) run once for each test file and may execute in parallel across different workers depending on the maxWorkers configuration.

    1. Initialization: Loading configuration and project setup.
    2. Global Setup: One-time setup before any tests run.
    3. Worker Creation: Spawning test workers based on pool configuration.
    4. Test File Collection: Discovering and organizing test files.
    5. Test Execution: Running tests with their associated hooks and assertions.
    6. Reporting: Collecting and reporting results.
    7. Global Teardown: Final cleanup after all tests complete.
  3. Overview of Vitest Pool Runners

    Vitest executes tests within a pool. By default, it provides several built-in pool runners for different isolation and execution needs:

    • threads: Uses node:worker_threads for isolation via new worker contexts.
    • forks: Uses node:child_process for isolation via child_process.fork processes.
    • vmThreads: Uses node:worker_threads but provides isolation via the vm module.
    • browser: Uses browser providers to run tests.
    • typescript: Used for typechecking tests.
  4. Overview of Component Testing with Vitest Browser Mode

    Component testing in Vitest focuses on verifying individual UI components in isolation. It is recommended to use Browser Mode (via Playwright, WebdriverIO, or preview mode) rather than DOM simulation libraries. Browser Mode ensures accuracy by testing actual DOM implementations, CSS rendering, browser APIs, event propagation, and accessibility features.
  5. Overview of Vitest Test Artifacts

    Test artifacts are a low-level API used to attach structured data, files, or metadata during test execution. They are primarily intended for framework authors creating custom tools or for internal Vitest use (e.g., the annotate feature is built on this system). For simple test notes or context, users should use test annotations instead. Each artifact consists of a unique type discriminator, custom data, optional attachments, and a source code location.
  6. Understand Vitest release cycles and version support

    Vitest follows Semantic Versioning (SemVer). Support is provided for the current minor version (regular fixes), the previous minor version, and the latest minor of the previous major version (important fixes and security patches). All older versions are unsupported.

    Release frequency:

    • Patch: As needed (usually weekly).
    • Minor: New features, released as needed (usually every two months) with a beta phase.
    • Major: Aligned with Vite and Node.js EOL schedules (usually yearly) with a long beta phase.
  7. Fix unawaited assertions in async Vitest tests

    If a test involving promises passes unexpectedly or triggers a warning about unawaited assertions, ensure the test function is async and the assertion is prefixed with await.
    // Correct way to handle async assertions
    test('fetches user', async () => {
      await expect(fetchUser(1)).resolves.toMatchObject({ name: 'Alice' })
    })
  8. Use the TestSuite class to inspect test suites

    The TestSuite class represents a single test suite and is available only in the main thread. You can identify a TestSuite instance by checking if its type property is equal to 'suite'. This is useful when iterating through tasks to distinguish between suites and individual tests.
    if (task.type === 'suite') {
      // task is a TestSuite
    }
  9. Understand the TestModule class

    The TestModule class represents a single module in a single project. It is only available in the main thread. It inherits all methods and properties from the TestSuite class. You can identify a TestModule instance by checking if its type property is equal to 'module'.
    if (task.type === 'module') {
      task // TestModule
    }
  10. Access global test state and snapshots

    Vitest provides global managers for state and snapshots:

    • state: Stores information about current tests. Use state.getReportedEntity(task) (Reported Tasks API) instead of the older state.idMap for better stability.
    • snapshot: The global snapshot manager. Use snapshot.add to track snapshots and access vitest.snapshot.summary for the latest summary.
    • cache: Stores latest test results and file stats, primarily used by the default sequencer to sort tests.
    // Recommended way to access test state
    const testCase = vitest.state.getReportedEntity(task)
  11. Inspect mock call history and arguments

    The mock property on a Vitest mock function provides metadata about its execution:

    • mock.calls: An array of all arguments for each call (e.g., [[arg1, arg2], [arg3]]).
    • mock.lastCall: The arguments of the most recent call.
    • mock.contexts: An array of this values used during each call.
    • mock.instances: An array of instances created when the mock was called with new.
    • mock.invocationCallOrder: A global sequence number indicating when this mock was called relative to others.
    const fn = vi.fn()
    fn('arg1', 'arg2')
    fn('arg3')
    
    console.log(fn.mock.calls) // [['arg1', 'arg2'], ['arg3']]
    console.log(fn.mock.lastCall) // ['arg3']
  12. Understand Vitest's relationship with Vite

    Vitest is a next-generation testing framework powered by Vite. It uses the same configuration as the application (via vite.config.js), sharing a common transformation pipeline across development, build, and test environments. This eliminates the need to configure separate pipelines for testing (as is often required with tools like Jest) and allows Vitest to leverage Vite's plugin API and instant Hot Module Replacement (HMR).