Vitest 17 🧪 Setup Files — Global Setup and Per-File Initialization
Vitest has two setup mechanisms that run at different times in different scopes. globalSetup runs once in the main thread before any test worker is created, and it is for the expensive setup that the whole run shares—a database server, a mock API, a port allocation. setupFiles runs before every test file in the same process as the tests, and it is for the per-file configuration—the testing-library matchers, the MSW handlers, the global mocks. The names are close enough that the wrong one produces a suite that starts the server once per file or registers the matchers once per run, and the distinction is the scope.
This chapter covers the globalSetup and setupFiles options, the provide/inject bridge that passes data from the global scope to the tests, and the configuration that keeps the per-file setup from repeating work. The sections that follow walk through the global setup, the per-file setup, and the data bridge that connects them.
Key point: globalSetup runs once in the main thread before the workers and cannot share globals with the tests—it passes data through project.provide() and the tests read it with inject(); setupFiles runs before every test file in the same process as the tests, and it is where the matchers and the per-file mocks belong.
a. globalSetup and the main-thread scope
globalSetup is a path or an array of paths to files that run once before the test workers are created . The file exports a named setup and teardown pair, or a default function that returns the teardown. The setup receives a TestProject object, and the teardown is called after all test files finish.
// globalSetup.ts
import type { TestProject } from "vitest/node";
export default function setup(project: TestProject) {
const server = startMockApi(); // expensive, once per run
project.provide("apiPort", server.port);
return function teardown() {
server.close();
};
}
The global setup runs in a different global scope from the tests. A variable defined in the setup file is not visible to the test files, which is the warning the documentation states explicitly . The provide/inject bridge is the mechanism for passing a value—a port, a URL, a token—from the setup to the tests.
// vitest.config.ts
export default defineConfig({
test: {
globalSetup: ["./globalSetup.ts"],
},
});
// a test file
import { inject } from "vitest";
test("uses the mock API", () => {
const port = inject("apiPort"); // the value from the setup
expect(port).toBeGreaterThan(0);
});
The declare module "vitest" augmentation types the ProvidedContext so the inject("apiPort") call is typed. The provide call is the only way to move a value from the global setup to the tests, and the value must be serializable.
The multiple global setup files run sequentially, and the teardowns run in reverse order . The onTestsRerun hook is the place to restart the mock server when the tests rerun in watch mode, because the global setup itself runs only once per process.
b. setupFiles and the per-file scope
setupFiles is a path or an array of paths to files that run before each test file in the same process as the tests . The file’s exports are ignored, which means the file runs for its side effects—the matcher registration, the global mock, the beforeEach cleanup.
// vitest.config.ts
export default defineConfig({
test: {
setupFiles: ["./test/setup.ts"],
},
});
// test/setup.ts
import "@testing-library/jest-dom/vitest";
import { cleanup } from "@testing-library/react";
import { afterEach } from "vitest";
afterEach(() => {
cleanup();
});
The per-file setup is the correct place for the testing-library cleanup, the custom matchers, and the MSW server lifecycle. The beforeAll(() => server.listen()), afterEach(() => server.resetHandlers()), and afterAll(() => server.close()) belong in the setup file, so every test file gets the same handlers without repeating the boilerplate .
The setup file runs once before each test file, not once per test. A beforeEach inside the setup file runs before every test in every file, and the afterEach runs after every test. The distinction matters: the setup file itself is the per-file boundary, and the hooks inside it are the per-test boundary.
The isolation caveat is the detail that catches a heavy setup. When isolate: false is set, the imported modules are cached, but the setup file itself executes again before each test file . A setup file that runs a heavy initialization on every execution runs it once per file, and the globalThis.setupInitialized guard is the pattern for skipping the repeated work.
// test/setup.ts
import { config } from "@some-testing-lib";
if (!globalThis.setupInitialized) {
config.plugins = [myCoolPlugin];
computeHeavyThing();
globalThis.setupInitialized = true;
}
The process.env.VITEST_POOL_ID is the worker identifier. A setup file that needs to distribute a workload across the workers reads the pool id and partitions the work, which is the pattern for a setup that allocates a per-worker resource.
c. The choice and the data bridge
The choice between the two is determined by the scope and the sharing. The globalSetup is for the resource that the whole run shares and the tests do not access directly—a server, a port, a database. The setupFiles is for the configuration the tests need in their own process—the matchers, the mocks, the cleanup.
The provide/inject bridge is the only channel from the global scope to the test scope. The global setup calls project.provide("key", value), and the test calls inject("key"). The ProvidedContext interface is the type declaration that makes the key type-safe.
// globalSetup.ts
export default function setup(project: TestProject) {
project.provide("dbUrl", "postgres://localhost:5432/test");
}
// global.d.ts
declare module "vitest" {
export interface ProvidedContext {
dbUrl: string;
}
}
// test.ts
import { inject } from "vitest";
const dbUrl = inject("dbUrl"); // typed as string
The per-file setup does not need the bridge. It runs in the test process, so a module-level variable it imports is the same variable the test imports. The setupFiles can set up a global, and the test can read it, because they share the global scope.
The two mechanisms compose. The globalSetup starts the server and provides the port; the setupFiles reads the port with inject and configures the test’s API client. The global setup owns the resource, and the per-file setup owns the client that talks to it.
Complete Example Session
// ============================================
// PART 1: THE GLOBAL SETUP
// ============================================
// globalSetup.ts
import type { TestProject } from "vitest/node";
export default function setup(project: TestProject) {
const server = startMockApi();
project.provide("apiPort", server.port);
return () => {
server.close();
};
}
// ============================================
// PART 2: THE PER-FILE SETUP
// ============================================
// test/setup.ts
import "@testing-library/jest-dom/vitest";
import { inject } from "vitest";
import { afterEach } from "vitest";
import { cleanup } from "@testing-library/react";
import { configureApi } from "./api-client";
// Use the value from the global setup
configureApi({ baseURL: `http://localhost:${inject("apiPort")}` });
afterEach(() => {
cleanup();
});
// ============================================
// PART 3: THE CONFIG
// ============================================
// vitest.config.ts
export default defineConfig({
test: {
globalSetup: ["./globalSetup.ts"],
setupFiles: ["./test/setup.ts"],
},
});
// ============================================
// PART 4: THE TEST
// ============================================
// src/user.test.ts
import { test, expect } from "vitest";
import { fetchUser } from "./api-client";
test("fetches a user from the mock API", async () => {
const user = await fetchUser("1");
expect(user.name).toBe("Ana");
});
The parts covered the global setup with the provide bridge, the per-file setup with the inject read, the config that registers both, and the test that uses the configured client.
Quick Reference
Global Setup vs Setup Files
| Aspect | globalSetup | setupFiles |
|---|---|---|
| Runs | Once per run | Before each file |
| Scope | Main thread | Test process |
| Shares globals | No | Yes |
| Data bridge | provide/inject | Module import |
| Use | Server, DB, port | Matchers, mocks, cleanup |
Global Setup API
| Export | Form |
|---|---|
| Named | export function setup(project) / export function teardown() |
| Default | export default function setup(project) { return teardown } |
| Data | project.provide("key", value) |
Config
| Option | Value |
|---|---|
globalSetup | ["./globalSetup.ts"] |
setupFiles | ["./test/setup.ts"] |
sequence.setupFiles | "list" or "parallel" |
Best Practices
✅ Do This:
// Use globalSetup for the shared server
globalSetup: ["./globalSetup.ts"] // ✅
// Use setupFiles for the matchers
setupFiles: ["./test/setup.ts"] // ✅
// Bridge the port with provide/inject
project.provide("apiPort", port); inject("apiPort"); // ✅
❌ Don’t Do This:
// Use globalSetup for the matchers
globalSetup: ["./matchers.ts"] // wrong scope // ❌
// Use setupFiles for the server
setupFiles: ["./server.ts"] // starts per file // ❌
// Rely on a global from the setup file
setupFiles: ["./set-global.ts"]; global.foo // works, but // ❌
// globalSetup cannot share this way
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Matchers not registered | Put in globalSetup | Move to setupFiles |
| Server starts per file | Put in setupFiles | Move to globalSetup |
inject returns undefined | No provide call | Add the provide |
| Heavy setup runs repeatedly | isolate: false | Guard with globalThis |
Real-World Examples
1. Global setup
export default function setup(project) { ... }
2. Setup files
setupFiles: ["./test/setup.ts"]
3. Provide a value
project.provide("apiPort", 3000);
4. Inject the value
const port = inject("apiPort");
5. Matcher registration
import "@testing-library/jest-dom/vitest";
6. Cleanup
afterEach(() => cleanup());
7. MSW lifecycle
beforeAll(() => server.listen());
8. Guard the heavy setup
if (!globalThis.setupInitialized) { ... }
9. Worker id
const pool = process.env.VITEST_POOL_ID;
10. Type the context
declare module "vitest" { interface ProvidedContext { apiPort: number } }
Visual
The Two Scopes
┌─────────────────────────────────────────────────────────┐
│ MAIN THREAD TEST PROCESS │
│ ┌──────────────────┐ ┌──────────────────┐ │
│ │ globalSetup │ │ setupFiles │ │
│ │ once per run │ │ per test file │ │
│ │ server, DB, port │ │ matchers, mocks │ │
│ └──────────────────┘ └──────────────────┘ │
│ │ │ │
│ └──────── provide/inject ──────┘ │
└─────────────────────────────────────────────────────────┘
The Global Setup Flow
┌─────────────────────────────────────────────────────────┐
│ globalSetup │
│ │ │
│ ▼ │
│ setup(project) → start server → project.provide(port) │
│ │ │
│ ▼ │
│ Workers created │
│ │ │
│ ▼ │
│ Tests run → inject("apiPort") │
│ │ │
│ ▼ │
│ teardown() → stop server │
└─────────────────────────────────────────────────────────┘
The Setup Files Flow
┌─────────────────────────────────────────────────────────┐
│ setupFiles │
│ │ │
│ ▼ │
│ Runs before test file 1 → matchers, cleanup │
│ Runs before test file 2 → matchers, cleanup │
│ Runs before test file 3 → matchers, cleanup │
│ │
│ Same process as the tests, so globals are shared. │
└─────────────────────────────────────────────────────────┘
Summary
| Item | Value |
|---|---|
| Global setup | globalSetup (once, main thread) |
| Per-file setup | setupFiles (every file, test process) |
| Data bridge | project.provide() / inject() |
| Global setup export | Named setup/teardown or default |
| Matchers | setupFiles |
| Server | globalSetup |
Key takeaways:
globalSetupruns once in the main thread, before the workers. It is for the shared resource—the server, the database, the port—and it cannot share globals with the tests. Theprovide/injectbridge is the only channel .setupFilesruns before every test file in the test process. It is for the per-file configuration—the matchers, the mocks, the cleanup—and it shares the global scope with the tests .- The
provide/injectbridge passes data from the global scope. The setup callsproject.provide("key", value), and the test callsinject("key"). TheProvidedContextinterface is the type declaration. - The setup file’s hooks are per-test, not per-file. A
beforeEachinside the setup file runs before every test in every file, and theafterEachruns after every test. - The heavy setup needs a guard when isolation is disabled. With
isolate: false, the setup file runs again before each file, and theglobalThis.setupInitializedguard skips the repeated work .
Remember: The two setup mechanisms have different scopes. globalSetup owns the shared resource, and setupFiles owns the per-file configuration. The global setup cannot see the tests’ globals, so it passes data through provide, and the tests read it with inject. Put the matchers and the cleanup in setupFiles, the server and the database in globalSetup, and the port in the provide call.
Stop using slow, ad-bloated tool sites! 🤮
🔎 Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)
⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free
🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!