Go back

Vitest timing breakdown

Last updated: 22.12.2024

Context:

  • Environment: SPA React Application with Vitest test runner
  • Dependencies:
    • Vitest version: "vitest": "2.1.8"

Problem:

Vitest after running tests prints out the Duration in the following format:

This data is from a real-world large project.

Test Files 424 passed | 1 skipped(425)
  Tests    1235 passed | 5 skipped (1240)
 Duration  285.14s (transform 9.01s, setup 2273.07s, collect 37.69s, tests 133.60s, environment 41.95s, prepare 19.43s)

Vitest Team provide basic information about it in their docs

Solution:

Basic breakdown:

  1. setup: sum of all setupFiles elements of your Vitest config file,run for each test file
  2. collect: file-system scan to gather your test files and import their dependencies
  3. tests: time for running only the tests
  4. transform: how long it takes for Vitest to transform files (source and tests)
  5. environment: overhead for loading the environment (importing jsdom/happy-dom/node)
  6. prepare: Vitest's internal tasks (setup cache, linking tests files)

Where to search for execution time improvements:

  1. setup:
  • try to move parts of the setup into a global setup/teardown if possible
  • try to run global fixtures once before all tests, instead of before each test
  1. collect:
  • keep testMatch, include and exclude precis, to avoid scanning unnecessary files.
  • in case you have a custom exclude or include make sure you are using: import { configDefaults } from 'vitest/config'
  1. tests:
  • refactor or remove slow or redundant tests
  • migrate the large DOM tests to tools like Cypress, Playwright, or Storybook UI Testing
  1. transform:
  • investigate barrel-files transformations (they might pull entire module)
  • investigate if tweaking babel/swc/typescript setup will help
  • investigate optimizeDeps in the config
  1. environment:
  • if you run your tests with Web API simulations, consider using happy-dom instead of JSDom
  • discover if setting the different environment in specific tests will improve performance (e.g. when using global jsdom, use node in test without need for jsdom)
  1. prepare:
  • reducing the amount of the dependencies used in the project is always beneficial
  • check for the circular dependencies in the project

To improve the performance you can check the dedicated docs on the Vitest documentation

Sources: