Reliability of globalTeardown in Vitest
The globalTeardown hook in Vitest is designed to execute once after all test suites have finished. However, its reliability depends heavily on how asynchronous operations are handled and the mode in which Vitest is running.
Execution Order and Nested Scopes
Vitest does not support "nested" globalTeardown configurations in the way it supports nested describe blocks. The globalTeardown is a top-level configuration property. If you have multiple teardown requirements, they must be orchestrated within a single function or handled via afterAll within individual suites. There is no built-in mechanism to register multiple independent global teardown files that guarantee a specific execution order across different config scopes.
Impact of Uncaught Exceptions
If an uncaught exception or a rejected promise occurs within globalTeardown, the following behaviors are observed:
- Exit Codes: A failure in the global teardown typically results in a non-zero exit code for the entire process, signaling a failure to the CI/CD pipeline even if all individual tests passed.
- Resource Leaks: Because the hook is a single execution point, an exception thrown early in the function will prevent any subsequent cleanup logic in that same block from running. This leads to leaked file handles or orphaned database connections.
- Iterations: In a standard CI run, the process terminates, and the OS eventually reclaims handles. However, in a persistent environment, these leaks persist until the process is killed.
Behavior in Watch Mode and Minimal Configs
Resource management differs significantly based on the runner's state:
| Scenario |
Behavior |
Resource Impact |
| Watch Mode |
Global hooks do not necessarily re-run on every file change. |
Stale state and leaked handles accumulate between re-runs. |
| Minimal Config |
globalTeardown is skipped entirely. |
Node.js relies on process exit; child processes may become orphaned. |
Verification Steps
To verify if your resources are leaking during teardown failures, you can use these scoped commands:
# 1. Trigger a failure in globalTeardown, then check the exit code
npm test && echo "Success" || echo "Failed with code $?"
# 2. Check for leaked ports/handles (Unix) during watch mode
lsof -i :
Diagnostic Requirement: To provide a more specific resolution for watch-mode leaks, please specify if you are using globalSetup to initialize these resources, as the lifecycle pairing determines if the state is truly global or suite-specific.