Configuring vitest.config.ts
What you'll learn: How to set up vitest.config.ts to extend your Vite configuration and establish the proper test environment for React components.
Why a Separate Config File?
While Vitest can read from your existing vite.config.ts, creating a dedicated vitest.config.ts gives you test-specific settings without polluting your build configuration. Think of it like having a backstage area separate from the main theater—both serve the same show, but each has different requirements.
The Basic Structure
Your vitest.config.ts should extend your Vite config using mergeConfig:
import { defineConfig, mergeConfig } from 'vite'
import viteConfig from './vite.config'
export default mergeConfig(
viteConfig,
defineConfig({
test: {
// Test-specific configuration goes here
},
})
)
Essential Test Environment Settings
For React testing, you need two critical configurations:
test: {
environment: 'jsdom', // Simulates browser DOM
globals: true, // Makes describe, it, expect globally available
}
environment: 'jsdom' creates a fake browser environment in Node.js, which React components need to render. Without this, you'd get errors about document and window being undefined.
globals: true lets you write describe() and it() without importing them in every test file—matching the Jest experience you may be familiar with.
Why This Matters
Vitest inherits Vite's module resolution, plugin system, and speed, but React components need DOM APIs that don't exist in Node.js. This config bridges that gap while keeping your test and build configurations cleanly separated.
Key Takeaway: A properly configured vitest.config.ts extends your Vite setup, adds jsdom for DOM simulation, and enables globals for a smoother testing experience.