Setup & Teardown Hooks in Vitest
From the Vitest cheat sheet · Hooks & Lifecycle · verified Nov 2026
Setup & Teardown Hooks
beforeAll, beforeEach, afterEach, afterAll, and per-test cleanup
typescript
beforeAll(async () => { await db.connect() })
afterAll(async () => { await db.disconnect() })
beforeEach(() => { store.reset() })
afterEach(() => { vi.useRealTimers() })
// Return a cleanup function instead of a matching after hook
beforeEach(() => {
const server = startServer()
return () => server.close()
})💡 Returning a function from beforeEach/beforeAll acts as teardown
⚠️ Arrow shorthand that returns a value can be taken as cleanup
📌 Hooks inside a describe apply only to tests in that block
⚡ onTestFinished keeps cleanup next to the code that needs it
hooksbeforeEachafterEachbeforeAll
Continue with Vitest
Save the full cheat sheet or work through every related task.