Per-Test Setup and Teardown
Perform per-test setup and teardown logic withbeforeEach and afterEach.
test.ts
Per-Scope Setup and Teardown
Perform per-scope setup and teardown logic withbeforeAll 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
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
--preload to run the setup script before any test files.
terminal
--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 abeforeAll hook throws, every test in its scope is skipped:
test.ts
test.ts
Best Practices
Keep Hooks Simple
test.ts
Use Appropriate Scope
test.ts
Clean Up Resources
test.ts