Files
bun.sh/docs/test/lifecycle.md
Colin McDonnell 109ebc14fd Various docs updates (#3437)
* Various docs updates

* Add mocks page

* Fix make

* WebKit instructions

* Update instructions

* Updates

* Update nodejs compat table

* Document trusted deps

* Tweak trustedDependencies docs

* Document --exact

* Update test docs

* Tweaks

* Boring

* Remove redundant j

* Undo makefile changes

* Undo makefile changes

* Update page title

* Regen

* Undo changes
2023-07-06 13:02:29 -07:00

1.7 KiB

The test runner supports the following lifecycle hooks. This is useful for loading test fixtures, mocking data, and configuring the test environment.

Hook Description
beforeAll Runs once before all tests.
beforeEach Runs before each test.
afterEach Runs after each test.
afterAll Runs once after all tests.

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

import { beforeEach, afterEach } from "bun:test";

beforeEach(() => {
  console.log("running test.");
});

afterEach(() => {
  console.log("done with test.");
});

// tests...

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

To scope the hooks to a particular describe block:

import { describe, beforeAll } from "bun:test";

describe("test group", () => {
  beforeAll(() => {
    // setup
  });

  // tests...
});

To scope the hooks to a test file:

import { describe, beforeAll } from "bun:test";

describe("test group", () => {
  beforeAll(() => {
    // setup
  });

  // tests...
});

To scope the hooks to an entire multi-file test run, define the hooks in a separate file.

import { beforeAll, afterAll } from "bun:test";

beforeAll(() => {
  // global setup
});

afterAll(() => {
  // global teardown
});

Then use --preload to run the setup script before any test files.

$ bun test --preload ./setup.ts

To avoid typing --preload every time you run tests, it can be added to your bunfig.toml:

[test]
preload = ["./setup.ts"]