Global Test Setup with setupFiles
What You'll Learn
You'll learn how to create a setup file that runs once before all tests, importing @testing-library/jest-dom matchers and configuring global test utilities.
Why Global Setup Matters
Without a setup file, you'd need to import @testing-library/jest-dom at the top of every single test file to get useful matchers like toBeInTheDocument() or toHaveClass(). Multiply that across dozens or hundreds of test files, and you've got repetitive boilerplate that's easy to forget.
The setupFiles option in Vitest solves this by running a configuration file once before your entire test suite starts, making utilities available everywhere automatically.
Creating Your Setup File
Create a file named vitest.setup.ts (or .js) in your project root:
// vitest.setup.ts
import '@testing-library/jest-dom';
Then reference it in your vitest.config.ts:
export default defineConfig({
test: {
environment: 'jsdom',
setupFiles: ['./vitest.setup.ts'],
},
});
Now every test file has access to extended matchers without individual imports.
What setupFiles Does
Think of setupFiles like a "pre-flight checklist" that runs before your plane (test suite) takes off. It configures the environment once, globally, so each individual test doesn't have to repeat the same setup steps.
You can also use this file for:
- Configuring global mocks
- Setting up test-wide environment variables
- Registering custom matchers
The import of @testing-library/jest-dom augments Vitest's expect with DOM-specific matchers, making your test assertions more readable and expressive.
Key Takeaway: Use setupFiles in your Vitest config to import @testing-library/jest-dom once globally, eliminating repetitive imports and ensuring consistent test utilities across your entire suite.