Skip to content
Tutorials Center
My learning

Topics

Lesson 26 of 39 ยท Testing

Your First Tests with bun test

Write tests with Bun's built-in Jest-compatible runner: test, describe, expect matchers, async tests, test.each, skipping and filtering, plus a runnable mini test runner.

Bun includes a test runner, so you need no Jest, Vitest or extra config to start. It understands TypeScript and JSX directly, its API is Jest-compatible (test, describe, expect), and it runs fast because it uses the same engine as the runtime. You write tests in files, run bun test, and read a short report.

Bun is not available on this site. The bun:test code below is read-only. To let you practice the ideas, the TryIt blocks use a tiny test runner written in plain Node that copies the test, describe and expect shape. It is a teaching stand-in, not Bun's runner.

Writing and running a first test

Say you have a function in src/math.ts:

TypeScript
export function add(a: number, b: number): number {
  return a + b;
}

export function clamp(n: number, min: number, max: number): number {
  return Math.min(Math.max(n, min), max);
}

Create src/math.test.ts next to it:

TypeScript
import { describe, expect, test } from "bun:test";
import { add, clamp } from "./math";

describe("math", () => {
  test("add sums two numbers", () => {
    expect(add(2, 3)).toBe(5);
  });

  test("clamp keeps a value inside the range", () => {
    expect(clamp(15, 0, 10)).toBe(10);
    expect(clamp(-4, 0, 10)).toBe(0);
    expect(clamp(7, 0, 10)).toBe(7);
  });
});

Run bun test. Bun searches the project for files named *.test.ts, *_test.ts, *.spec.ts or *_spec.ts (and the .js, .jsx, .tsx, .mjs, .cjs equivalents), runs each one, and prints a line per test with a check mark or a cross plus a summary of passes, failures and time. The exit code is non-zero on failure, so it works in CI as is.

Useful command-line forms:

TEXT
bun test                      # everything
bun test src/math             # files whose path contains "src/math"
bun test -t "clamp"           # only tests whose NAME matches the pattern
bun test --watch              # rerun on file changes
bun test --bail               # stop after the first failure
bun test --timeout 10000      # per-test timeout in ms (default 5000)

A test fails when it throws. expect(...) matchers throw when the expectation is not met, and so does any plain exception.

The matchers you will use daily

TypeScript
expect(1 + 1).toBe(2);                         // Object.is: primitives and identity
expect({ a: 1, b: [2] }).toEqual({ a: 1, b: [2] });   // deep equality
expect({ a: 1, b: undefined }).toStrictEqual({ a: 1, b: undefined }); // stricter
expect([1, 2, 3]).toContain(2);
expect("hello world").toMatch(/world/);
expect(0.1 + 0.2).toBeCloseTo(0.3);            // floats
expect(5).toBeGreaterThan(3);
expect(null).toBeNull();
expect(undefined).toBeUndefined();
expect("x").toBeTruthy();
expect([1, 2]).toHaveLength(2);
expect({ name: "Ada", age: 36 }).toHaveProperty("name", "Ada");
expect({ name: "Ada", age: 36 }).toMatchObject({ name: "Ada" });
expect(() => JSON.parse("{")).toThrow();        // function must throw
expect(() => { throw new RangeError("bad"); }).toThrow(RangeError);
expect(5).not.toBe(6);                         // negate any matcher

toBe compares with Object.is, so two equal-looking objects are not toBe: use toEqual. Prefer the most specific matcher; toHaveLength(2) gives a clearer failure message than expect(arr.length).toBe(2).

Node.js A mini test runner with the bun:test shape (Node stand-in)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or process.stdin), it gets the next line from this box.

Change the two lines marked "fails on purpose" and watch the report turn green.

Async tests and timeouts

Return a promise or use async; Bun waits for it. A test that never settles fails after the timeout.

TypeScript
import { expect, test } from "bun:test";

test("fetches a user", async () => {
  const user = await findUser(1);
  expect(user.name).toBe("Ada");
});

test("rejects for a missing user", async () => {
  await expect(findUser(999)).rejects.toThrow("not found");
});

test("resolves with a value", async () => {
  await expect(Promise.resolve(42)).resolves.toBe(42);
});

Do not forget await before expect(...).rejects: without it the test finishes before the assertion runs and a failure is silently lost. Give one slow test its own limit with a third argument: test("big job", async () => { ... }, 30_000).

Table tests with test.each

When the same assertion applies to many inputs, write the cases as data:

TypeScript
import { expect, test } from "bun:test";
import { clamp } from "./math";

test.each([
  [15, 0, 10, 10],
  [-4, 0, 10, 0],
  [7, 0, 10, 7],
])("clamp(%d, %d, %d) = %d", (n, min, max, expected) => {
  expect(clamp(n, min, max)).toBe(expected);
});

%d is a number, %s a string, %p pretty-printed, %j JSON. Each row becomes its own test with its own name and result.

Skip, focus and mark work

TypeScript
test.skip("not ready yet", () => {});          // reported as skipped
test.todo("support negative ranges");           // a reminder, shows as todo
test.only("run just this one", () => {});       // with `bun test --only`
test.failing("known bug", () => { throw new Error("bug"); }); // passes while it still fails
test.if(process.platform === "linux")("linux only", () => {});

.only takes effect when you run bun test --only, which prevents a stray .only from silently skipping your whole suite in CI. test.todo and test.failing keep known problems visible without breaking the build.

Where tests live

Two layouts are common. Colocated: math.ts and math.test.ts side by side, easy to find and refactor together. Separate folder: a top-level tests/ directory, tidy for larger apps and integration tests. Bun does not care. Pick one, and let bun run test (a script that calls bun test, see scripts) be what teammates and CI use.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which file name does bun test pick up automatically?

    Bun runs files named .test., _test., .spec. and _spec..
  2. 2. Why does expect({a:1}).toBe({a:1}) fail?

    toBe checks identity. Use toEqual for deep equality of contents.
  3. 3. What is the danger of writing expect(promise).rejects.toThrow() without await?

    Without await the test function returns before the promise settles, so the assertion's result is lost.
  4. 4. How do you run only tests whose name contains "clamp"?

    -t (or --test-name-pattern) filters by test name; a bare argument filters by file path.

Summary

  • bun test finds *.test.ts-style files, runs them with a Jest-compatible API and exits non-zero on failures.
  • Core matchers: toBe, toEqual, toStrictEqual, toContain, toMatch, toBeCloseTo, toThrow, .not.
  • Async tests return or await promises; use .resolves / .rejects with await.
  • test.each turns data tables into many tests; skip, todo, only, failing, if manage work in progress.
  • Filter with a path argument, -t for names, --watch and --bail while developing.

Next: Mocks, Spies and Fake Time