Vitest Configuration Mechanics: Merging vite.config.ts, test.include, and Environment Drivers
Mastering test environments (happy-dom vs jsdom), workspace overrides, and inclusion rules.
Part 4 in Series — Catch up on the previous article: Worker Thread Pool Isolation: How Tinypool & Worker Threads Execute Tests in Parallel (Part 3) before diving into this post.
Vitest reads your application’s vite.config.ts automatically. You don’t need a separate config file for testing unless you want to isolate test settings from your production build pipeline.
When Vitest starts, it merges the test block inside vite.config.ts into Vite’s root configuration object.
// vite.config.ts
import { defineConfig } from 'vite';
import react from '@vitejs/plugin-react';
import { defineConfig as defineVitestConfig } from 'vitest/config';
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'@': '/src',
},
},
test: {
globals: true,
environment: 'happy-dom',
include: ['src/**/*.{test,spec}.{ts,tsx}'],
exclude: ['node_modules', 'dist', '.idea'],
setupFiles: ['./src/test/setup.ts'],
},
});
Choosing a Test Environment: happy-dom vs jsdom vs node
By default, Vitest runs in a node environment. When testing browser components or DOM logic, you specify a simulated browser environment.
| Feature | happy-dom | jsdom | node |
|---|---|---|---|
| Startup Speed | ~10-20ms | ~80-150ms | 0ms |
| Memory Usage | Extremely Low | Moderate/High | Minimal |
| HTML5 Specs | Partial/Fast | Strict/Full | None |
| Recommended For | React/Vue components | Complex Web APIs | Unit/Logic tests |
happy-dom is significantly faster than jsdom because it omits complex spec-compliant HTML parsing details that unit tests rarely rely on.
// Custom per-file environment directive
// @vitest-environment jsdom
import { test, expect } from 'vitest';
test('DOM test using jsdom override', () => {
document.body.innerHTML = '<button id="btn">Click</button>';
expect(document.getElementById('btn')).not.toBeNull();
});
Vitest allows overriding the environment per file using docblock annotations at the top of the file, giving you fine-grained control over execution speed.
Part 5: Assertion Engine Mechanics: First-Principles Comparison of Vitest Matchers
Continue to Part 5 →