Vitest timing breakdown
Last updated: 22.12.2024
Context:
- Environment: SPA React Application with Vitest test runner
- Dependencies:
- Vitest version: "vitest": "2.1.8"
 
- Vitest version: 
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:
- setup: sum of all- setupFileselements of your Vitest config file,run for each test file
- collect: file-system scan to gather your test files and import their dependencies
- tests: time for running only the tests
- transform: how long it takes for Vitest to transform files (source and tests)
- environment: overhead for loading the environment (importing jsdom/happy-dom/node)
- prepare: Vitest's internal tasks (setup cache, linking tests files)
Where to search for execution time improvements:
Please, measure before optimizing: https://vitest.dev/guide/profiling-test-performance.html
- 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
- collect:
- keep testMatch,includeandexcludeprecis, to avoid scanning unnecessary files.
- in case you have a custom excludeorincludemake sure you are using:import { configDefaults } from 'vitest/config'
- tests:
- refactor or remove slow or redundant tests
- migrate the large DOM tests to tools like Cypress, Playwright, or Storybook UI Testing
- transform:
- investigate barrel-files transformations (they might pull entire module)
- investigate if tweaking babel/swc/typescript setup will help
- investigate optimizeDeps in the config
- 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)
- 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: