gentleeduck/duck-ui / .claude/skills/vitest
vitest
VerifiedVitest fast unit testing framework powered by Vite with Jest-compatible API. Use when writing tests, mocking, configuring coverage, or working with test filtering and fixtures.
| File | Kind | Size |
|---|---|---|
| GENERATION.md | markdown | 136 B |
| SKILL.md | skill md | 3.6 KB |
| agents/openai.yaml | config | 98 B |
| references/advanced-environments.md | markdown | 4.7 KB |
| references/advanced-projects.md | markdown | 5.4 KB |
| references/advanced-type-testing.md | markdown | 4.6 KB |
| references/advanced-vi.md | markdown | 5.6 KB |
| references/core-cli.md | markdown | 4.1 KB |
| references/core-config.md | markdown | 4.7 KB |
| references/core-describe.md | markdown | 3.5 KB |
| references/core-expect.md | markdown | 6.6 KB |
| references/core-hooks.md | markdown | 4.8 KB |
| references/core-test-api.md | markdown | 5.3 KB |
| references/features-benchmarking.md | markdown | 3.6 KB |
| references/features-concurrency.md | markdown | 4.7 KB |
| references/features-context.md | markdown | 5.3 KB |
| references/features-coverage.md | markdown | 4.2 KB |
| references/features-filtering.md | markdown | 3.8 KB |
| references/features-mocking.md | markdown | 6.9 KB |
| references/features-reporters.md | markdown | 3.7 KB |
| references/features-snapshots.md | markdown | 5.2 KB |
| references/features-test-tags.md | markdown | 3.6 KB |
references/core-hooks.md
View on GitHub---
name: lifecycle-hooks
description: beforeEach, afterEach, beforeAll, afterAll, and around hooks
---
# Lifecycle Hooks
## Basic Hooks
```ts
import { afterAll, afterEach, beforeAll, beforeEach, test } from 'vitest'
beforeAll(async () => {
// Runs once before all tests in file/suite
await setupDatabase()
})
afterAll(async () => {
// Runs once after all tests in file/suite
await teardownDatabase()
})
beforeEach(async () => {
// Runs before each test
await clearTestData()
})
afterEach(async () => {
// Runs after each test
await cleanupMocks()
})
```
## Cleanup Return Pattern
Return cleanup function from `before*` hooks:
```ts
beforeAll(async () => {
const server = await startServer()
// Returned function runs as afterAll
return async () => {
await server.close()
}
})
beforeEach(async () => {
const connection = await connect()
// Runs as afterEach
return () => connection.close()
})
```
## Scoped Hooks
Hooks apply to current suite and nested suites:
```ts
describe('outer', () => {
beforeEach(() => console.log('outer before'))
test('test 1', () => {}) // outer before → test
describe('inner', () => {
beforeEach(() => console.log('inner before'))
test('test 2', () => {}) // outer before → inner before → test
})
})
```
## Hook Timeout
```ts
beforeAll(async () => {
await slowSetup()
}, 30_000) // 30 second timeout
```
## Around Hooks
Wrap tests with setup/teardown context:
```ts
import { aroundEach, test } from 'vitest'
// Wrap each test in database transaction
aroundEach(async (runTest) => {
await db.beginTransaction()
await runTest() // Must be called!
await db.rollback()
})
test('insert user', async () => {
await db.insert({ name: 'Alice' })
// Automatically rolled back after test
})
```
### aroundAll
Wrap entire suite:
```ts
import { aroundAll, test } from 'vitest'
aroundAll(async (runSuite) => {
console.log('before all tests')
await runSuite() // Must be called!
console.log('after all tests')
})
```
### Multiple Around Hooks
Nested like onion layers:
```ts
aroundEach(async (runTest) => {
console.log('outer before')
await runTest()
console.log('outer after')
})
aroundEach(async (runTest) => {
console.log('inner before')
await runTest()
console.log('inner after')
})
// Order: outer before → inner before → test → inner after → outer after
```
## Test Hooks
Inside test body:
```ts
import { onTestFailed, onTestFinished, test } from 'vitest'
test('with cleanup', () => {
const db = connect()
// Runs after test finishes (pass or fail)
onTestFinished(() => db.close())
// Only runs if test fails
onTestFailed(({ task }) => {
console.log('Failed:', task.result?.errors)
})
db.query('SELECT * FROM users')
})
```
### Reusable Cleanup Pattern
```ts
function useTestDb() {
const db = connect()
onTestFinished(() => db.close())
return db
}
test('query users', () => {
const db = useTestDb()
expect(db.query('SELECT * FROM users')).toBeDefined()
})
test('query orders', () => {
const db = useTestDb() // Fresh connection, auto-closed
expect(db.query('SELECT * FROM orders')).toBeDefined()
})
```
## Concurrent Test Hooks
For concurrent tests, use context's hooks:
```ts
test.concurrent('concurrent', ({ onTestFinished }) => {
const resource = allocate()
onTestFinished(() => resource.release())
})
```
## Extended Test Hooks
With `test.extend`, hooks are type-aware and must be called on the extended `test`:
```ts
const test = base
.extend('db', { scope: 'file' }, async ({}, { onCleanup }) => {
const db = await createDb()
onCleanup(() => db.close())
return db
})
// Test-level hooks see fixtures
test.beforeEach(({ db }) => db.seed())
test.afterEach(({ db }) => db.clear())
// Suite-level hooks (4.1+) can access file/worker-scoped fixtures
test.beforeAll(({ db }) => db.createUsers())
test.aroundAll(async (runSuite, { db }) => db.transaction(runSuite))
```
Suite-level hooks (`beforeAll`/`afterAll`/`aroundAll`) only see **file/worker-scoped** fixtures, and the **global** `beforeAll`/`afterAll` cannot access custom fixtures — use `test.beforeAll` etc.
## Hook Execution Order
Default order (stack):
1. `beforeAll` (in order)
2. `beforeEach` (in order)
3. Test
4. `afterEach` (reverse order)
5. `afterAll` (reverse order)
Configure with `sequence.hooks`:
```ts
defineConfig({
test: {
sequence: {
hooks: 'list', // 'stack' (default), 'list', 'parallel'
},
},
})
```
## Key Points
- Hooks are not called during type checking
- Return cleanup function from `before*` to avoid `after*` duplication
- `aroundEach`/`aroundAll` must call `runTest()`/`runSuite()`
- `onTestFinished` always runs, even if test fails
- Use context hooks for concurrent tests
<!--
Source references:
- https://vitest.dev/api/hooks.html
-->
Related skills
| Skill | Stars | Updated | Works with | Status | Install |
|---|---|---|---|---|---|
| finishing-a-development-branchobra/superpowersUse when implementation is complete, all tests pass, and you need to decide how to integrate the work | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| systematic-debuggingobra/superpowersUse when encountering any bug, test failure, or unexpected behavior, before proposing fixes | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| test-driven-developmentobra/superpowersUse when implementing any feature or bugfix, before writing implementation code | Stars: 322k | Updated | Claude CodeCodex | Verified | Install |
| skill-creatoranthropics/skillsCreate new skills, modify and improve existing skills, and measure skill performance. Use when users want to create a skill from scratch, edit, or optimize an existing skill, run evals to test a skill, benchmark skill performance with variance analysis, or optimize a skill's description for better triggering accuracy. | Stars: 198k | Updated | Claude CodeCodex | Verified | Install |