···7788- **Type:** `string | string[]`
991010-Path to global setup files, relative to project root.
1010+Path to global setup files relative to project [root](/config/root).
11111212-A global setup file can either export named functions `setup` and `teardown` or a `default` function that returns a teardown function ([example](https://github.com/vitest-dev/vitest/blob/main/test/global-setup/vitest.config.ts)).
1212+A global setup file can either export named functions `setup` and `teardown` or a `default` function that returns a teardown function:
13131414-::: info
1515-Multiple globalSetup files are possible. setup and teardown are executed sequentially with teardown in reverse order.
1414+::: code-group
1515+```js [exports]
1616+export function setup(project) {
1717+ console.log('setup')
1818+}
1919+2020+export function teardown() {
2121+ console.log('teardown')
2222+}
2323+```
2424+```js [default]
2525+export default function setup(project) {
2626+ console.log('setup')
2727+2828+ return function teardown() {
2929+ console.log('teardown')
3030+ }
3131+}
3232+```
1633:::
17341818-::: warning
1919-Global setup runs only if there is at least one running test. This means that global setup might start running during watch mode after test file is changed (the test file will wait for global setup to finish before running).
3535+Note that the `setup` method and a `default` function receive a [test project](/api/advanced/test-project) as the first argument. The global setup is called before the test workers are created and only if there is at least one test queued, and teardown is called after all test files have finished running. In [watch mode](/config/watch), the teardown is called before the process is exited instead. If you need to reconfigure your setup before the test rerun, you can use [`onTestsRerun`](#handling-test-reruns) hook instead.
20362121-Beware that the global setup is running in a different global scope, so your tests don't have access to variables defined here. However, you can pass down serializable data to tests via [`provide`](#provide) method:
3737+Multiple global setup files are possible. `setup` and `teardown` are executed sequentially with teardown in reverse order.
3838+3939+::: danger
4040+Beware that the global setup is running in a different global scope before test workers are even created, so your tests don't have access to global variables defined here. However, you can pass down serializable data to tests via [`provide`](/config/provide) method and read them in your tests via `inject` imported from `vitest`:
22412342:::code-group
2424-```ts [example.test.js]
4343+```ts [example.test.ts]
2544import { inject } from 'vitest'
26452746inject('wsPort') === 3000
2847```
2929-```ts [globalSetup.ts <Version>3.0.0</Version>]
4848+```ts [globalSetup.ts]
3049import type { TestProject } from 'vitest/node'
31503251export default function setup(project: TestProject) {
···3958 }
4059}
4160```
4242-```ts [globalSetup.ts <Version>2.0.0</Version>]
4343-import type { GlobalSetupContext } from 'vitest/node'
44614545-export default function setup({ provide }: GlobalSetupContext) {
4646- provide('wsPort', 3000)
4747-}
4848-4949-declare module 'vitest' {
5050- export interface ProvidedContext {
5151- wsPort: number
5252- }
5353-}
5454-```
6262+If you need to execute code in the same process as tests, use [`setupFiles`](/config/setupfiles) instead, but note that it runs before every test file.
5563:::
56645757-Since Vitest 3, you can define a custom callback function to be called when Vitest reruns tests. If the function is asynchronous, the runner will wait for it to complete before executing tests. Note that you cannot destruct the `project` like `{ onTestsRerun }` because it relies on the context.
6565+### Handling Test Reruns
6666+6767+You can define a custom callback function to be called when Vitest reruns tests. The test runner will wait for it to complete before executing tests. Note that you cannot destruct the `project` like `{ onTestsRerun }` because it relies on the context.
58685969```ts [globalSetup.ts]
6070import type { TestProject } from 'vitest/node'
+2-2
docs/config/sequence.md
···26262727If [`sequencer.groupOrder`](#grouporder) is specified, the sequencer will be called once for each group and pool.
28282929-## groupOrder
2929+## sequence.groupOrder
30303131- **Type:** `number`
3232- **Default:** `0`
···97979898If you want files and tests to run randomly, you can enable it with this option, or CLI argument [`--sequence.shuffle`](/guide/cli).
9999100100-Vitest usually uses cache to sort tests, so long running tests start earlier - this makes tests run faster. If your files and tests will run in random order you will lose this performance improvement, but it may be useful to track tests that accidentally depend on another run previously.
100100+Vitest usually uses cache to sort tests, so long-running tests start earlier, which makes tests run faster. If your files and tests run in random order, you will lose this performance improvement, but it may be useful to track tests that accidentally depend on another test run previously.
101101102102### sequence.shuffle.files {#sequence-shuffle-files}
103103
+14-8
docs/config/setupfiles.md
···7788- **Type:** `string | string[]`
991010-Path to setup files. They will be run before each test file.
1010+Paths to setup files resolved relative to the [`root`](/config/root). They will run before each _test file_ in the same process. By default, all test files run in parallel, but you can configure it with [`sequence.setupFiles`](/config/sequence#sequence-setupfiles) option.
1111+1212+Vitest will ignore any exports from these files.
1313+1414+:::warning
1515+Note that setup files are executed in the same process as tests, unlike [`globalSetup`](/config/globalsetup) that runs once in the main thread before any test worker is created.
1616+:::
11171218:::info
1319Editing a setup file will automatically trigger a rerun of all tests.
1420:::
15211616-You can use `process.env.VITEST_POOL_ID` (integer-like string) inside to distinguish between workers.
2222+If you have a heavy process running in the background, you can use `process.env.VITEST_POOL_ID` (integer-like string) inside to distinguish between workers and spread the workload.
17231818-:::tip
1919-Note, that if you are running [`--isolate=false`](#isolate), this setup file will be run in the same global scope multiple times. Meaning, that you are accessing the same global object before each test, so make sure you are not doing the same thing more than you need.
2020-:::
2424+:::warning
2525+If [isolation](/config/isolate) is disabled, imported modules are cached, but the setup file itself is executed again before each test file, meaning that you are accessing the same global object before each test file. Make sure you are not doing the same thing more than necessary.
21262227For example, you may rely on a global variable:
23282429```ts
2530import { config } from '@some-testing-lib'
26312727-if (!globalThis.defined) {
3232+if (!globalThis.setupInitialized) {
2833 config.plugins = [myCoolPlugin]
2934 computeHeavyThing()
3030- globalThis.defined = true
3535+ globalThis.setupInitialized = true
3136}
32373333-// hooks are reset before each suite
3838+// hooks reset before each test file
3439afterEach(() => {
3540 cleanup()
3641})
37423843globalThis.resetBeforeEachTest = true
3944```
4545+:::
+320
docs/guide/lifecycle.md
···11+---
22+title: Test Run Lifecycle | Guide
33+outline: deep
44+---
55+66+# Test Run Lifecycle
77+88+Understanding the test run lifecycle is essential for writing effective tests, debugging issues, and optimizing your test suite. This guide explains when and in what order different lifecycle phases occur in Vitest, from initialization to teardown.
99+1010+## Overview
1111+1212+A typical Vitest test run goes through these main phases:
1313+1414+1. **Initialization** - Configuration loading and project setup
1515+2. **Global Setup** - One-time setup before any tests run
1616+3. **Worker Creation** - Test workers are spawned based on the [pool](/config/pool) configuration
1717+4. **Test File Collection** - Test files are discovered and organized
1818+5. **Test Execution** - Tests run with their hooks and assertions
1919+6. **Reporting** - Results are collected and reported
2020+7. **Global Teardown** - Final cleanup after all tests complete
2121+2222+Phases 4–6 run once for each test file, so across your test suite they will execute multiple times and may also run in parallel across different files when you use more than [1 worker](/config/maxworkers).
2323+2424+## Detailed Lifecycle Phases
2525+2626+### 1. Initialization Phase
2727+2828+When you run `vitest`, the framework first loads your configuration and prepares the test environment.
2929+3030+**What happens:**
3131+- [Command-line](/guide/cli) arguments are parsed
3232+- [Configuration file](/config/) is loaded
3333+- Project structure is validated
3434+3535+This phase can run again if the config file or one of its imports changes.
3636+3737+**Scope:** Main process (before any test workers are created)
3838+3939+### 2. Global Setup Phase
4040+4141+If you have configured [`globalSetup`](/config/globalsetup) files, they run once before any test workers are created.
4242+4343+**What happens:**
4444+- `setup()` functions (or exported `default` function) from global setup files execute sequentially
4545+- Multiple global setup files run in the order they are defined
4646+4747+**Scope:** Main process (separate from test workers)
4848+4949+**Important notes:**
5050+- Global setup runs in a **different global scope** from your tests
5151+- Tests cannot access variables defined in global setup (use [`provide`/`inject`](/config/provide) instead)
5252+- Global setup only runs if there is at least one test queued
5353+5454+```ts [globalSetup.ts]
5555+export function setup(project) {
5656+ // Runs once before all tests
5757+ console.log('Global setup')
5858+5959+ // Share data with tests
6060+ project.provide('apiUrl', 'http://localhost:3000')
6161+}
6262+6363+export function teardown() {
6464+ // Runs once after all tests
6565+ console.log('Global teardown')
6666+}
6767+```
6868+6969+### 3. Worker Creation Phase
7070+7171+After global setup completes, Vitest creates test workers based on your [pool configuration](/config/pool).
7272+7373+**What happens:**
7474+- Workers are spawned according to the `browser.enabled` or `pool` setting (`threads`, `forks`, `vmThreads`, or `vmForks`)
7575+- Each worker gets its own isolated environment (unless [isolation](/config/isolate) is disabled)
7676+- By default, workers are not reused to provide isolation. Workers are reused only if:
7777+ - [isolation](/config/isolate) is disabled
7878+ - OR pool is `vmThreads` or `vmForks` because [VM](https://nodejs.org/api/vm.html) provides enough isolation
7979+8080+**Scope:** Worker processes/threads
8181+8282+### 4. Test File Setup Phase
8383+8484+Before each test file runs, [setup files](/config/setupfiles) are executed.
8585+8686+**What happens:**
8787+- Setup files run in the same process as your tests
8888+- By default, setup files run in **parallel** (configurable via [`sequence.setupFiles`](/config/sequence#sequence-setupfiles))
8989+- Setup files execute before **each test file**
9090+- Any global _state_ or configuration can be initialized here
9191+9292+**Scope:** Worker process (same as your tests)
9393+9494+**Important notes:**
9595+- If [isolation](/config/isolate) is disabled, setup files still rerun before each test file to trigger side effects, but imported modules are cached
9696+- Editing a setup file triggers a rerun of all tests in watch mode
9797+9898+```ts [setupFile.ts]
9999+import { afterEach } from 'vitest'
100100+101101+// Runs before each test file
102102+console.log('Setup file executing')
103103+104104+// Register hooks that apply to all tests
105105+afterEach(() => {
106106+ cleanup()
107107+})
108108+```
109109+110110+### 5. Test Collection and Execution Phase
111111+112112+This is the main phase where your tests actually run.
113113+114114+#### Test File Execution Order
115115+116116+Test files are executed based on your configuration:
117117+118118+- **Sequential by default** within a worker
119119+- Files will run in **parallel** across different workers, configured by [`maxWorkers`](/config/maxworkers)
120120+- Order can be randomized with [`sequence.shuffle`](/config/sequence#sequence-shuffle) or fine-tuned with [`sequence.sequencer`](/config/sequence#sequence-sequencer)
121121+- Long-running tests typically start earlier (based on cache) unless shuffle is enabled
122122+123123+#### Within Each Test File
124124+125125+The execution follows this order:
126126+127127+1. **File-level code** - All code outside `describe` blocks runs immediately
128128+2. **Test collection** - `describe` blocks are processed, and tests are registered as side effects of importing the test file
129129+3. **`beforeAll` hooks** - Run once before any tests in the suite
130130+4. **For each test:**
131131+ - `beforeEach` hooks execute (in order defined, or based on [`sequence.hooks`](/config/sequence#sequence-hooks))
132132+ - Test function executes
133133+ - `afterEach` hooks execute (reverse order by default with `sequence.hooks: 'stack'`)
134134+ - [`onTestFinished`](/api/#ontestfinished) callbacks run (always in reverse order)
135135+ - If test failed: [`onTestFailed`](/api/#ontestfailed) callbacks run
136136+ - Note: if `repeats` or `retry` are set, all of these steps are executed again
137137+5. **`afterAll` hooks** - Run once after all tests in the suite complete
138138+139139+**Example execution flow:**
140140+141141+```ts
142142+// This runs immediately (collection phase)
143143+console.log('File loaded')
144144+145145+describe('User API', () => {
146146+ // This runs immediately (collection phase)
147147+ console.log('Suite defined')
148148+149149+ beforeAll(() => {
150150+ // Runs once before all tests in this suite
151151+ console.log('beforeAll')
152152+ })
153153+154154+ beforeEach(() => {
155155+ // Runs before each test
156156+ console.log('beforeEach')
157157+ })
158158+159159+ test('creates user', () => {
160160+ // Test executes
161161+ console.log('test 1')
162162+ })
163163+164164+ test('updates user', () => {
165165+ // Test executes
166166+ console.log('test 2')
167167+ })
168168+169169+ afterEach(() => {
170170+ // Runs after each test
171171+ console.log('afterEach')
172172+ })
173173+174174+ afterAll(() => {
175175+ // Runs once after all tests in this suite
176176+ console.log('afterAll')
177177+ })
178178+})
179179+180180+// Output:
181181+// File loaded
182182+// Suite defined
183183+// beforeAll
184184+// beforeEach
185185+// test 1
186186+// afterEach
187187+// beforeEach
188188+// test 2
189189+// afterEach
190190+// afterAll
191191+```
192192+193193+#### Nested Suites
194194+195195+When using nested `describe` blocks, hooks follow a hierarchical pattern:
196196+197197+```ts
198198+describe('outer', () => {
199199+ beforeAll(() => console.log('outer beforeAll'))
200200+ beforeEach(() => console.log('outer beforeEach'))
201201+202202+ test('outer test', () => console.log('outer test'))
203203+204204+ describe('inner', () => {
205205+ beforeAll(() => console.log('inner beforeAll'))
206206+ beforeEach(() => console.log('inner beforeEach'))
207207+208208+ test('inner test', () => console.log('inner test'))
209209+210210+ afterEach(() => console.log('inner afterEach'))
211211+ afterAll(() => console.log('inner afterAll'))
212212+ })
213213+214214+ afterEach(() => console.log('outer afterEach'))
215215+ afterAll(() => console.log('outer afterAll'))
216216+})
217217+218218+// Output:
219219+// outer beforeAll
220220+// outer beforeEach
221221+// outer test
222222+// outer afterEach
223223+// inner beforeAll
224224+// outer beforeEach
225225+// inner beforeEach
226226+// inner test
227227+// inner afterEach (with stack mode)
228228+// outer afterEach (with stack mode)
229229+// inner afterAll
230230+// outer afterAll
231231+```
232232+233233+#### Concurrent Tests
234234+235235+When using `test.concurrent` or [`sequence.concurrent`](/config/sequence#sequence-concurrent):
236236+237237+- Tests within the same file can run in parallel
238238+- Each concurrent test still runs its own `beforeEach` and `afterEach` hooks
239239+- Use [test context](/guide/test-context) for concurrent snapshots: `test.concurrent('name', async ({ expect }) => {})`
240240+241241+### 6. Reporting Phase
242242+243243+Throughout the test run, reporters receive lifecycle events and display results.
244244+245245+**What happens:**
246246+- Reporters receive events as tests progress
247247+- Results are collected and formatted
248248+- Test summaries are generated
249249+- Coverage reports are generated (if enabled)
250250+251251+For detailed information about the reporter lifecycle, see the [Reporters](/api/advanced/reporters) guide.
252252+253253+### 7. Global Teardown Phase
254254+255255+After all tests complete, global teardown functions execute.
256256+257257+**What happens:**
258258+- `teardown()` functions from [`globalSetup`](/config/globalsetup) files run
259259+- Multiple teardown functions run in **reverse order** of their setup
260260+- In watch mode, teardown runs before process exit, not between test reruns
261261+262262+**Scope:** Main process
263263+264264+```ts [globalSetup.ts]
265265+export function teardown() {
266266+ // Clean up global resources
267267+ console.log('Global teardown complete')
268268+}
269269+```
270270+271271+## Lifecycle in Different Scopes
272272+273273+Understanding where code executes is crucial for avoiding common pitfalls:
274274+275275+| Phase | Scope | Access to Test Context | Runs |
276276+|-------|-------|----------------------|------|
277277+| Config File | Main process | ❌ No | Once per Vitest run |
278278+| Global Setup | Main process | ❌ No (use `provide`/`inject`) | Once per Vitest run |
279279+| Setup Files | Worker (same as tests) | ✅ Yes | Before each test file |
280280+| File-level code | Worker | ✅ Yes | Once per test file |
281281+| `beforeAll` / `afterAll` | Worker | ✅ Yes | Once per suite |
282282+| `beforeEach` / `afterEach` | Worker | ✅ Yes | Per test |
283283+| Test function | Worker | ✅ Yes | Once (or more with retries/repeats) |
284284+| Global Teardown | Main process | ❌ No | Once per Vitest run |
285285+286286+## Watch Mode Lifecycle
287287+288288+In watch mode, the lifecycle repeats with some differences:
289289+290290+1. **Initial run** - Full lifecycle as described above
291291+2. **On file change:**
292292+ - New [test run](/api/advanced/reporters#ontestrunstart) starts
293293+ - Only affected test files are re-run
294294+ - [Setup files](/config/setupfiles) run again for those test files
295295+ - [Global setup](/config/globalsetup) does **not** re-run (use [`project.onTestsRerun`](/config/globalsetup#handling-test-reruns) for rerun-specific logic)
296296+3. **On exit:**
297297+ - Global teardown executes
298298+ - Process terminates
299299+300300+## Performance Considerations
301301+302302+Understanding the lifecycle helps optimize test performance:
303303+304304+- **Global setup** is ideal for expensive one-time operations (database seeding, server startup)
305305+- **Setup files** run before each test file - avoid heavy operations here if you have many test files
306306+- **`beforeAll`** is better than `beforeEach` for expensive setup that doesn't need isolation
307307+- **Disabling [isolation](/config/isolate)** improves performance, but setup files still execute before each file
308308+- **[Pool configuration](/config/pool)** affects parallelization and available APIs
309309+310310+For tips on how to improve performance, read the [Improving Performance](/guide/improving-performance) guide.
311311+312312+## Related Documentation
313313+314314+- [Global Setup Configuration](/config/globalsetup)
315315+- [Setup Files Configuration](/config/setupfiles)
316316+- [Test Sequencing Options](/config/sequence)
317317+- [Isolation Configuration](/config/isolate)
318318+- [Pool Configuration](/config/pool)
319319+- [Extending Reporters](/guide/advanced/reporters) - for reporter lifecycle events
320320+- [Test API Reference](/api/) - for hook APIs and test functions