Skip to main content
Bun’s test runner provides lifecycle hooks to set up and tear down test state. These hooks are compatible with Jest.

Available hooks

beforeAll

Runs once before all tests in a describe block:

beforeEach

Runs before each test:

afterEach

Runs after each test:

afterAll

Runs once after all tests in a describe block:

Async hooks

All hooks support async operations:

Hook execution order

Hooks execute in the following order:
  1. beforeAll (outer describe)
  2. beforeAll (inner describe)
  3. beforeEach (outer describe)
  4. beforeEach (inner describe)
  5. test
  6. afterEach (inner describe)
  7. afterEach (outer describe)
  8. afterAll (inner describe)
  9. afterAll (outer describe)
Example:

Scoping

Hooks are scoped to the describe block they’re defined in:

Timeout

Hooks can have custom timeouts:

Done callback

Hooks support the done callback pattern:
Prefer using async/await over done callbacks when possible.

Error handling

If a hook throws an error:
  • beforeAll/beforeEach: The test is marked as failed
  • afterEach/afterAll: The test result is preserved, but the error is logged

Resource cleanup with using

Bun supports JavaScript’s using keyword for automatic resource cleanup: