Sub topic 13
Configuring Vitest with vitest.config
Vitest runs with no configuration at all, and that is how the earlier chapters used it. Real projects soon need more control. They need to decide where tests live, what runs before every test file, how long a slow test may take, and whether mocks reset between tests. This chapter covers the configuration file that holds those settings, how Vitest finds it, and the settings you will change most often.
This chapter assumes you can already write and run tests with describe, it, and expect, and that you know vi.fn, vi.spyOn, and the lifecycle hooks from earlier chapters. Test environments and coverage each get their own chapter later. Here they appear only as configuration keys.
The configuration file
A Vitest configuration file exports an object, and the test key of that object holds the Vitest options. The defineConfig helper from vitest/config returns the object unchanged. Its value is editor support: autocompletion and type checking for every option.
// vitest.config.js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
include: ['src/**/*.test.js'],
testTimeout: 10000,
},
})Vitest is built on Vite, so the file can also hold Vite options such as resolve.alias or plugins. These go at the top level, beside test, and never inside it. If you put a Vite option inside test, Vitest ignores it without any warning.
The file can be written in JavaScript or TypeScript: vitest.config.js, .mjs, .ts, or .mts. Vite bundles the config file before it loads it, so ES module syntax works. Still, set "type": "module" in package.json or use the .mjs or .ts extension, so the file is treated the same way as the rest of your ES module code.
How Vitest finds its configuration
Vitest looks for a configuration in a fixed order, and the first match wins.
Two consequences of this order cause confusion:
- If a project has both
vite.config.jsandvitest.config.js, Vitest reads onlyvitest.config.js. Aliases and plugins defined in the Vite file are lost in tests unless you merge them in, as shown below. - If you only have
vite.config.js, you can add atestkey to it and skip the second file. ImportdefineConfigfromvitest/configinstead ofviteso thetestkey is typed.
Reusing an existing Vite configuration
When an app already has a Vite config, keep it as the single source of truth and layer test settings on top with mergeConfig:
// vitest.config.js
import { defineConfig, mergeConfig } from 'vitest/config'
import viteConfig from './vite.config.js'
export default mergeConfig(
viteConfig,
defineConfig({
test: {
setupFiles: ['./vitest.setup.js'],
},
}),
)mergeConfig merges deeply. Arrays are concatenated and nested objects are combined, so the test config adds to the Vite settings without replacing them. If vite.config.js exports a function instead of an object, call it first with the mode and command you want, then merge the result.
Settings you will change most often
The table lists the options this chapter covers, with their defaults.
| Option | Default | What it controls | Column |
|---|---|---|---|
| `include` | `['**/*.{test,spec}.?(c\ | m)[jt]s?(x)']` | Glob patterns for test files |
| `exclude` | `node_modules`, `dist`, and a few tool folders | Glob patterns removed from `include` | |
| `globals` | `false` | Whether `describe`, `it`, `expect`, `vi` exist without imports | |
| `environment` | `'node'` | The runtime globals tests see (covered next chapter) | |
| `setupFiles` | `[]` | Files run before each test file | |
| `testTimeout` | `5000` ms | Maximum time for one test | |
| `hookTimeout` | `10000` ms | Maximum time for one hook | |
| `clearMocks` | `false` | Calls `vi.clearAllMocks()` before each test | |
| `mockReset` | `false` | Calls `vi.resetAllMocks()` before each test | |
| `restoreMocks` | `false` | Calls `vi.restoreAllMocks()` before each test | |
| `reporters` | `['default']` | How results are printed |
Choosing which files are tests
include replaces the default pattern completely. exclude also replaces its default, and that causes a common mistake. If you write exclude: ['e2e/**'], Vitest stops excluding node_modules, and it may start running tests that ship inside your dependencies. Spread the defaults back in:
// vitest.config.js
import { defineConfig, configDefaults } from 'vitest/config'
export default defineConfig({
test: {
exclude: [...configDefaults.exclude, 'e2e/**'],
},
})Global APIs
With globals: true, test files can call describe, it, expect, and vi without importing them, the way Jest works. This makes migrating from Jest easier. The cost is that dependencies become implicit, and linters and TypeScript don't know about the globals. In TypeScript, add "types": ["vitest/globals"] to compilerOptions in tsconfig.json. For ESLint, declare the globals in its configuration. Explicit imports, as used in this tutorial, need none of that setup.
Setup files
Each file in setupFiles runs before every test file, in the same module context as that test file. Hooks registered in a setup file therefore apply to every test in the suite. That makes setup files a good home for cleanup you never want to forget:
// vitest.setup.js
import { afterEach, vi } from 'vitest'
afterEach(() => {
vi.useRealTimers()
})// vitest.config.js
import { defineConfig } from 'vitest/config'
export default defineConfig({
test: {
setupFiles: ['./vitest.setup.js'],
},
})Resetting mocks automatically
The spies chapter called vi.restoreAllMocks() in an afterEach hook. The three mock options do the same kind of work from config, before each test:
clearMockserases recorded calls and results but keeps any implementation you set.mockResetalso removes implementations you set, such asmockReturnValue.restoreMocksrestores the original methods behindvi.spyOnspies.
A suite where tests never leak mock state into one another usually sets restoreMocks: true, and adds clearMocks: true if it also shares vi.fn() instances across tests. Exactly what restoreMocks resets changed in Vitest 3, so check the docs for the version you use if a test depends on the details.
Timeouts
A test that runs longer than testTimeout fails with a timeout error. Raise the limit for one slow test with the third argument to it, for example it('imports a large file', async () => { /* ... */ }, 20000), and keep the global value low. A low global timeout catches promises that never settle, while one high global value hides them.
Overriding config from the command line
CLI flags take priority over the file. That makes them useful for one-off runs and for CI scripts:
npx vitest run --testTimeout=20000
npx vitest run --reporter=verbose
npx vitest --config ./vitest.integration.config.jsA common pattern defines both kinds of run in package.json:
{
"type": "module",
"scripts": {
"test": "vitest",
"test:ci": "vitest run --reporter=verbose"
}
}Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `ReferenceError: describe is not defined` | `globals` is off and the file has no imports | Import from `vitest` or set `globals: true` |
| Aliases work in the app but not in tests | `vitest.config.js` shadows `vite.config.js` | Use `mergeConfig` |
| Tests from `node_modules` run | `exclude` replaced the defaults | Spread `configDefaults.exclude` |
| Option has no effect | Placed outside `test`, or a Vite option placed inside it | Check the nesting |
| Setup file changes ignored | Path is wrong relative to the project root | Use `./` paths from the config file's folder |
Exercise
Your project has a vite.config.js that defines an alias '@' pointing at ./src. You add a vitest.config.js containing only test: { setupFiles: ['./vitest.setup.js'] }. Now imports like '@/utils.js' fail in tests. Explain why and write a vitest.config.js that fixes it.
Show answer
When vitest.config.js exists, Vitest loads only that file and never reads vite.config.js, so the alias is gone. Merge the two: import { defineConfig, mergeConfig } from 'vitest/config'; import viteConfig from './vite.config.js'; export default mergeConfig(viteConfig, defineConfig({ test: { setupFiles: ['./vitest.setup.js'] } })).
Exercise
A teammate sets exclude: ['*/.e2e.test.js'] and the next run reports hundreds of failing tests from inside node_modules. What happened and what is the correct setting?
Show answer
A custom exclude replaces the default list, which normally excludes node_modules and dist. The correct setting keeps the defaults: import { configDefaults } from 'vitest/config' and use exclude: [...configDefaults.exclude, '*/.e2e.test.js'].
Exercise
Tests in your suite use vi.spyOn and vi.fn, and some tests fail only when run after certain others. Which config options address this, and what does each one do before each test?
Show answer
Set restoreMocks: true so spies created with vi.spyOn have their original methods restored. Add clearMocks: true to erase recorded calls on shared vi.fn mocks, or mockReset: true if you also want to remove implementations set with mockReturnValue or mockImplementation.