provide & inject (Global Setup) in Vitest

From the Vitest cheat sheet ยท Test Context & Fixtures ยท verified Nov 2026

provide & inject (Global Setup)

Start shared services once and pass serializable values to every test file

typescript
// global-setup.ts
import type { TestProject } from 'vitest/node'

export default function setup(project: TestProject) {
  project.provide('apiPort', 4000)
}

// any.test.ts
import { inject } from 'vitest'
const port = inject('apiPort')   // 4000
๐Ÿ“Œ globalSetup runs in a separate scope; share data via provide/inject
๐Ÿ’ก Declare ProvidedContext so inject() is fully typed
โšก Return a function from setup to tear down after the whole run
๐Ÿ” setupFiles run per test file; globalSetup runs once per run
globalSetupprovideinject

Continue with Vitest

Save the full cheat sheet or work through every related task.

More Vitest tasks

Back to the full Vitest cheat sheet