Setting Up Before Tests with –preload in Bun’s bun test
When you add --preload ./setup.ts to bun test, setup.ts runs once before the test files. The beforeAll and afterAll hooks registered there run once each, at the start and end of the whole test run. The beforeEach and afterEach hooks run once for every test in every file.
This is a way to put setup that should happen before every test in one place, such as setting environment variables, starting a test server, or registering custom expect matchers. The migration guide from Jest says that preload corresponds to Jest's setupFiles and setupFilesAfterEnv. Below, I show the order things run in and some pitfalls, using output from actually running them in my test environment.
The test environment was Ubuntu 24.04 (x86_64, 4 cores) with Bun 1.4.4. For type checking, I used TypeScript 5.9.3 and @types/bun 1.4.4. The working directory paths in the output are replaced with /path/to/preload-demo. I did not test macOS, Windows, or the combination of --parallel with --no-isolate.
Writing environment variables and hooks in preload
First, I'll show what happens without preload, using two test files that read the environment variable API_URL. I prepared tests/a.test.ts and tests/b.test.ts.
// tests/a.test.ts
import { test, expect, beforeAll, afterAll } from "bun:test";
console.log("[a.test.ts] ファイルの先頭を実行");
beforeAll(() => console.log("[a.test.ts] beforeAll"));
afterAll(() => console.log("[a.test.ts] afterAll"));
test("a1: API_URL が入っている", () => {
console.log("[a.test.ts] a1 の本体");
expect(process.env.API_URL).toBe("http://192.0.2.10:3001");
});
test("a2", () => {
console.log("[a.test.ts] a2 の本体");
});
tests/b.test.ts is a file with one test, b1, that also checks API_URL, like a1 does. It also prints a console.log at the top. When I ran it with plain bun test, the two tests that check API_URL failed with Received: undefined (part of the output is omitted).
$ bun test ./tests/a.test.ts ./tests/b.test.ts
error: expect(received).toBe(expected)
Expected: "http://192.0.2.10:3001"
Received: undefined
(fail) a1: API_URL が入っている [0.36ms]
(中略)
1 pass
2 fail
2 expect() calls
Ran 3 tests across 2 files. [4.00ms]
So I created setup.ts, which sets the environment variable and registers four kinds of hooks.
// setup.ts
import { beforeAll, afterAll, beforeEach, afterEach } from "bun:test";
console.log("[setup.ts] ファイルの先頭を実行");
process.env.API_URL = "http://192.0.2.10:3001";
beforeAll(() => console.log("[setup.ts] beforeAll"));
afterAll(() => console.log("[setup.ts] afterAll"));
beforeEach(() => console.log("[setup.ts] beforeEach"));
afterEach(() => console.log("[setup.ts] afterEach"));
With --preload ./setup.ts, all three tests passed.
$ bun test --preload ./setup.ts ./tests/a.test.ts ./tests/b.test.ts
bun test v1.4.4 (38afee6c8)
tests/a.test.ts:
[setup.ts] ファイルの先頭を実行
[a.test.ts] ファイルの先頭を実行
[setup.ts] beforeAll
[a.test.ts] beforeAll
[setup.ts] beforeEach
[a.test.ts] a1 の本体
[setup.ts] afterEach
[setup.ts] beforeEach
[a.test.ts] a2 の本体
[setup.ts] afterEach
[a.test.ts] afterAll
tests/b.test.ts:
[b.test.ts] ファイルの先頭を実行
[setup.ts] beforeEach
[b.test.ts] b1 の本体
[setup.ts] afterEach
[setup.ts] afterAll
3 pass
0 fail
2 expect() calls
Ran 3 tests across 2 files. [4.00ms]
The output shows the following order:
- The top level of
setup.tsran once, before the first test file. It did not run again beforeb.test.ts. setup.ts'sbeforeAllran once, before the first test. ItsafterAllran once, after the last file finished.setup.ts'sbeforeEachandafterEachran for each test in botha.test.tsandb.test.ts.
The lifecycle page of the official documentation also describes writing setup and teardown that span multiple files in a separate file and loading it with --preload. An example of registering happy-dom in preload to use document is covered in a separate article, "How to write DOM tests with bun test and happy-dom."
In bunfig.toml, put it inside [test]
To avoid typing --preload every time, you can put it in [test] in bunfig.toml. The official documentation on test configuration says that listing multiple files in an array and passing --preload multiple times have the same meaning.
[test]
preload = ["./cfg.ts"]
I confirmed three things here.
First, multiple preloads run in the order they are written. With --preload ./first.ts --preload ./second.ts, first.ts ran first. When I swapped the order, second.ts ran first.
Second, when bunfig.toml has [test].preload and you also pass --preload, both run and the CLI option does not replace the config. The bunfig.toml one ran first (output lines such as the test counts are omitted).
$ bun test --preload ./first.ts tests/c.test.ts
bun test v1.4.4 (38afee6c8)
tests/c.test.ts:
[cfg.ts] 実行(bunfig.toml の [test].preload)
[first.ts] 実行
[c.test.ts] ファイルの先頭を実行
Third, a preload written outside [test] (at the top of the file) did not run under bun test. I tested this with a bunfig.toml that contained only the following line (output lines such as the test counts are omitted).
preload = ["./top.ts"]
$ bun test tests/c.test.ts
bun test v1.4.4 (38afee6c8)
tests/c.test.ts:
[c.test.ts] ファイルの先頭を実行
$ bun plain.ts
[top.ts] 実行(bunfig.toml の先頭の preload)
[plain.ts] 実行
When I ran a file directly, as in bun plain.ts, top.ts ran. Under bun test, it did not. The official bunfig.toml reference says that a top-level preload runs before bun run executes a file or script. Put test setup inside [test].
Starting a test server with await
In a preload file, you can use top-level await. The following server/setup-server.ts waits 300 milliseconds in place of slow setup, starts a server with Bun.serve, and stores its URL in an environment variable. The server is stopped in afterAll.
// server/setup-server.ts
import { afterAll } from "bun:test";
const t0 = performance.now();
await Bun.sleep(300); // stands in for setup that takes a while
const server = Bun.serve({
port: 0,
fetch(req) {
return Response.json({ path: new URL(req.url).pathname });
},
});
process.env.TEST_SERVER_URL = server.url.href;
console.log(`[setup-server.ts] サーバーを起動(${Math.round(performance.now() - t0)}ms)`);
afterAll(async () => {
await server.stop();
console.log("[setup-server.ts] サーバーを停止");
});
port: 0 tells the OS to choose an unused port. There are two test files. Each one calls fetch on process.env.TEST_SERVER_URL and only checks the JSON that comes back.
// server/users.test.ts
import { test, expect } from "bun:test";
test("/users を取得できる", async () => {
const res = await fetch(new URL("/users", process.env.TEST_SERVER_URL));
expect(await res.json()).toEqual({ path: "/users" });
});
$ bun test --preload ./server/setup-server.ts ./server
bun test v1.4.4 (38afee6c8)
server/users.test.ts:
[setup-server.ts] サーバーを起動(302ms)
server/items.test.ts:
[setup-server.ts] サーバーを停止
2 pass
0 fail
2 expect() calls
Ran 2 tests across 2 files. [309.00ms]
The first test ran only after await finished and the server had started. The server started once for the whole run and stopped after the last file finished.
Registering custom matchers
Custom matchers created with expect.extend can also be registered in preload, which makes them available in every test file. I created toBePostalCode, which checks whether a value has the shape of a Japanese postal code (123-4567).
// matcher/matchers.ts
import { expect } from "bun:test";
expect.extend({
toBePostalCode(received: unknown) {
const pass = typeof received === "string" && /^\d{3}-\d{4}$/.test(received);
return {
pass,
message: () =>
`「${received}」は郵便番号の形(123-4567)${pass ? "です" : "ではありません"}`,
};
},
});
I ran tests that check "100-0001" and "1000001" without preload. Both failed with TypeError: expect("100-0001").toBePostalCode is not a function. With --preload ./matcher/matchers.ts, the first test passed and the second failed with the message written in the matcher (part of the output is omitted).
$ bun test --preload ./matcher/matchers.ts ./matcher
error: expect(received).toBePostalCode()
「1000001」は郵便番号の形(123-4567)ではありません
at <anonymous> (/path/to/preload-demo/matcher/postal.test.ts:7:21)
(fail) 1000001 は郵便番号の形 [0.18ms]
1 pass
1 fail
The tests run, but the TypeScript type check (tsc) reports Property 'toBePostalCode' does not exist on type 'Matchers<string>'. As described in the official guide's Testing Library setup, add the type of toBePostalCode to Matchers in a type declaration file.
// matcher/custom-matchers.d.ts
import "bun:test";
declare module "bun:test" {
interface Matchers<T> {
toBePostalCode(): void;
}
}
At first I named this file matchers.d.ts, the same base name as matchers.ts. With that name, the tsc error did not go away. When I renamed it to custom-matchers.d.ts, the error stopped.
What happens when preload fails
When an exception is thrown in a preload file, an error is shown under the heading # Unhandled error between tests, and the exit code is 1. The console.log at the top of c.test.ts was not printed, and the test file was not run, but the run is still counted as 1 fail.
$ bun test --preload ./broken.ts tests/c.test.ts
bun test v1.4.4 (38afee6c8)
tests/c.test.ts:
[broken.ts] 実行
# Unhandled error between tests
-------------------------------
1 | console.log("[broken.ts] 実行");
2 | throw new Error("テスト用の設定が足りません");
^
error: テスト用の設定が足りません
at /path/to/preload-demo/broken.ts:2:11
-------------------------------
0 pass
1 fail
1 error
Ran 1 test across 1 file. [4.00ms]
When I got the file name wrong, it stopped without running any tests, printing error: preload not found "./nothing.ts" with exit code 1.
With –isolate or –parallel, preload runs per file
The "preload runs only once" behavior described so far applies to plain bun test. With --isolate, preload runs again from the top for each file, and beforeAll and afterAll also ran per file.

According to the official documentation on parallel execution, --isolate creates a new global for each file and runs preload again. --parallel includes --isolate. When I tried this with the server example, the server started once per file in both modes.
$ bun test --isolate --preload ./server/setup-server.ts ./server
bun test v1.4.4 (38afee6c8)
server/users.test.ts:
[setup-server.ts] サーバーを起動(302ms)
[setup-server.ts] サーバーを停止
server/items.test.ts:
[setup-server.ts] サーバーを起動(302ms)
[setup-server.ts] サーバーを停止
2 pass
0 fail
2 expect() calls
Ran 2 tests across 2 files. [612.00ms]
With --isolate, the 300-millisecond setup ran twice in a row, and the whole run took 612 ms. With --parallel=2, the two files ran at the same time, and the whole run took 323 ms.
With --isolate or --parallel, heavy preload setup is repeated once per test file. For setup you want to do only once, such as creating a database or starting a server, decide whether to run with plain bun test or with --isolate or --parallel before you write it in preload.





