Skip to main content
The test runner supports the following lifecycle hooks. Use them to load test fixtures, mock data, and configure the test environment.

Per-Test Setup and Teardown

Perform per-test setup and teardown logic with beforeEach and afterEach.
test.ts

Per-Scope Setup and Teardown

Perform per-scope setup and teardown logic with beforeAll and afterAll. The scope is determined by where the hook is defined.

Scoped to a Describe Block

To scope the hooks to a particular describe block:
test.ts

Scoped to a Test File

To scope the hooks to an entire test file:
test.ts

onTestFinished

Use onTestFinished to run a callback after a single test completes. It runs after all afterEach hooks.
test.ts
Not supported in concurrent tests; use test.serial instead.

Global Setup and Teardown

To scope the hooks to an entire multi-file test run, define the hooks in a separate file.
setup.ts
Then use --preload to run the setup script before any test files.
terminal
To avoid typing --preload every time you run tests, add it to your bunfig.toml:
bunfig.toml

Practical Examples

Database Setup

database-setup.ts

API Server Setup

server-setup.ts

Mock Setup

mock-setup.ts

Async Lifecycle Hooks

All lifecycle hooks support async functions:
test.ts

Nested Hooks

Hooks can be nested. They run in the following order:
test.ts

Error Handling

If a beforeAll hook throws, every test in its scope is skipped:
test.ts
To log a setup failure and still fail the suite:
test.ts

Best Practices

Keep Hooks Simple

test.ts

Use Appropriate Scope

test.ts

Clean Up Resources

test.ts