日本語

Running TypeScript Tests with bun test in Bun

​​Bun​Testing,TypeScript

Bun includes a test runner similar to Jest. Running bun test runs TypeScript tests directly. You don't need a config file or any test library to install. This article is for people who want to get started quickly with unit tests for TypeScript functions. It covers how to write tests, how to read failure output, how to run only some tests, coverage, and type checking, based on output from runs in my test environment.

Note

My test environment was Ubuntu 24.04 (x86_64) with Bun 1.4.4. I did not test Windows or macOS, --watch (re-running when files change), snapshot tests, UI tests that use the DOM, or running on a CI service. The official Bun documentation links below point to the source files at the tag bun-v1.4.4, which I checked on GitHub.

Put the test file in place and run bun test

First, prepare the function to test. This is src/cart.ts, which calculates the shopping cart subtotal, the coupon discount, and the shipping fee.

ts
export type Item = { name: string; price: number; qty: number };

// Subtotal of the items (before tax)
export function subtotal(items: Item[]): number {
  return items.reduce((sum, item) => sum + item.price * item.qty, 0);
}

// Amount after applying the coupon
export function applyCoupon(total: number, code: string): number {
  if (code === "OFF10") return Math.floor(total * 0.9);
  if (code === "MINUS500") return Math.max(total - 500, 0);
  throw new Error(`unknown coupon: ${code}`);
}

// Shipping fee (free at 5000 yen or more)
export function shippingFee(total: number): number {
  return total >= 5000 ? 0 : 600;
}

Write the test in the same folder as src/cart.test.ts. Import test, describe, and expect from bun:test. The syntax is almost the same as Jest.

ts
import { describe, expect, test } from "bun:test";
import { applyCoupon, shippingFee, subtotal } from "./cart";

describe("subtotal", () => {
  test("単価と個数をかけて足す", () => {
    const items = [
      { name: "ノート", price: 300, qty: 2 },
      { name: "ペン", price: 120, qty: 3 },
    ];
    expect(subtotal(items)).toBe(960);
  });

  test("空のカートは0円", () => {
    expect(subtotal([])).toBe(0);
  });
});

describe("applyCoupon", () => {
  test("OFF10は1割引き(1円未満は切り捨て)", () => {
    expect(applyCoupon(999, "OFF10")).toBe(899);
  });

  test("知らないコードはエラーにする", () => {
    expect(() => applyCoupon(1000, "FREE")).toThrow("unknown coupon: FREE");
  });
});

describe("shippingFee", () => {
  test.each([
    [4999, 600],
    [5000, 0],
    [12000, 0],
  ])("合計 %d 円なら送料 %d 円", (total, fee) => {
    expect(shippingFee(total)).toBe(fee);
  });
});

test.each runs the same test many times with different values. In the test name, %d is replaced with the values from each row. To check that a function throws an error, wrap the call in a function, pass it to expect, and give the expected message to toThrow.

The folder contains only these two files. There is no package.json or tsconfig.json. I ran bun test here.

text
$ bun test
bun test v1.4.4 (38afee6c8)

src/cart.test.ts:
(pass) subtotal > 単価と個数をかけて足す [0.14ms]
(pass) subtotal > 空のカートは0円 [0.01ms]
(pass) applyCoupon > OFF10は1割引き(1円未満は切り捨て) [0.08ms]
(pass) applyCoupon > 知らないコードはエラーにする [0.20ms]
(pass) shippingFee > 合計 4999 円なら送料 600 円 [0.02ms]
(pass) shippingFee > 合計 5000 円なら送料 0 円
(pass) shippingFee > 合計 12000 円なら送料 0 円

 7 pass
 0 fail
 7 expect() calls
Ran 7 tests across 1 file. [4.00ms]

All 7 tests passed, in 4.00ms total. Test names are shown by joining the describe name and the test name with >. The 3 cases from test.each each appear as a separate line, with the values filled into %d.

bun test walks down from the current folder and runs files matching *.test.ts, *_test.ts, *.spec.ts, or *_spec.ts (js, jsx, tsx, and other extensions also work). It skips node_modules and folders whose names start with .. These rules are described in the official documentation on test file discovery.

Install @types/bun for editor completion

If you only want to run tests, the steps so far are enough. However, without more setup, there are no type definitions for bun:test. If you run a type check, you get a Cannot find module 'bun:test' error (this appears in the type checking section below). The official TypeScript page recommends installing @types/bun as a dev dependency.

text
$ bun add -d @types/bun
bun add v1.4.4 (38afee6c8)
Saved lockfile

installed @types/bun@1.4.4

4 packages installed [9.00ms]

Since there was no package.json, bun add created one.

json
{
  "dependencies": {},
  "devDependencies": {
    "@types/bun": "^1.4.4"
  }
}

In tsconfig.json, I added the following settings from the recommended settings in the official documentation. "types": ["bun"] loads the Bun types.

json
{
  "compilerOptions": {
    "lib": ["ESNext"],
    "target": "ESNext",
    "module": "Preserve",
    "moduleResolution": "bundler",
    "types": ["bun"],
    "strict": true,
    "noEmit": true,
    "skipLibCheck": true
  }
}

After this, I ran bun test again and confirmed that the result did not change, with all 7 tests passing.

How to read the output when a test fails

I deliberately changed the condition in shippingFee from total >= 5000 to total > 5000. This introduces a bug where the shipping fee is not free at exactly 5000 yen.

text
$ bun test
bun test v1.4.4 (38afee6c8)

src/cart.test.ts:
(pass) subtotal > 単価と個数をかけて足す [0.17ms]
(pass) subtotal > 空のカートは0円 [0.02ms]
(pass) applyCoupon > OFF10は1割引き(1円未満は切り捨て) [0.10ms]
(pass) applyCoupon > 知らないコードはエラーにする [0.08ms]
(pass) shippingFee > 合計 4999 円なら送料 600 円 [0.02ms]
29 |   test.each([
30 |     [4999, 600],
31 |     [5000, 0],
32 |     [12000, 0],
33 |   ])("合計 %d 円なら送料 %d 円", (total, fee) => {
34 |     expect(shippingFee(total)).toBe(fee);
                                    ^
error: expect(received).toBe(expected)

Expected: 0
Received: 600

      at <anonymous> (/path/to/cart-app/src/cart.test.ts:34:32)
(fail) shippingFee > 合計 5000 円なら送料 0 円 [0.19ms]
(pass) shippingFee > 合計 12000 円なら送料 0 円

 6 pass
 1 fail
 7 expect() calls
Ran 7 tests across 1 file. [5.00ms]

(In the at line, I replaced the folder path from my test environment with /path/to/.)

The name of the failed test appears below the error with (fail). Above the (fail) line, the failing expect line is shown with ^, and you can see that Expected (the expected value) was 0 and Received (the actual value) was 600. Of the 3 cases from test.each, only the 5000 yen case failed. Because I included the boundary value in test.each, this mistake was found.

At this point, the exit code of bun test was 1. When all tests pass, it is 0. If you want CI or similar to stop when tests fail, use this exit code.

When you run it directly in a terminal, the output is colored, and ✓ and ✗ are shown instead of (pass) and (fail).

Terminal output when one bun test fails. The failing line has ✗, the expected 0 is shown in green, and the received 600 is shown in red
Failure output from running in a terminal (partial). Paths are replaced with /path/to/

Run only some files or tests

Here I added another test file: src/price.ts, which takes a tax-rate function as an argument and returns the tax-included amount.

ts
// Takes the tax rate from outside and returns the tax-included amount
export async function withTax(
  total: number,
  getRate: () => Promise<number>,
): Promise<number> {
  const rate = await getRate();
  return Math.floor(total * (1 + rate));
}

In the test, I create a function that returns the tax rate with mock and pass it in. A function created with mock remembers how many times it was called, so you can also use toHaveBeenCalledTimes to confirm it was called exactly once. When testing an async function, make the test function async too and use await.

ts
import { expect, mock, test } from "bun:test";
import { withTax } from "./price";

test("税率を1回だけ取りに行き、税込みにする", async () => {
  const getRate = mock(async () => 0.1);

  const result = await withTax(1000, getRate);

  expect(result).toBe(1100);
  expect(getRate).toHaveBeenCalledTimes(1);
});

Now bun test runs 8 tests across the 2 files (8 pass, Ran 8 tests across 2 files).

Filter by file

If you put text after bun test, it runs only the test files whose paths contain that text.

text
$ bun test price
bun test v1.4.4 (38afee6c8)

src/price.test.ts:
(pass) 税率を1回だけ取りに行き、税込みにする [0.27ms]

 1 pass
 0 fail
 2 expect() calls
Ran 1 test across 1 file. [3.00ms]

This is a partial path match, not a glob pattern. To specify one exact file, the official documentation says to start the path with ./ or /, as in ./src/price.test.ts. In my test environment, both ./src/price.test.ts and src/price.test.ts ran the same single test.

Filter by test name

To select tests by name, use -t (--test-name-pattern). Names include the describe name, so you can select all tests inside a describe by giving its name. However, the names matched by -t are joined with spaces, not with > as in the output. In my test environment, -t 'shippingFee 合計 5000' selected one test, while -t 'shippingFee > 合計 5000' matched no tests and caused an error.

text
$ bun test -t 送料
bun test v1.4.4 (38afee6c8)

src/cart.test.ts:
(pass) shippingFee > 合計 4999 円なら送料 600 円 [0.03ms]
(pass) shippingFee > 合計 5000 円なら送料 0 円
(pass) shippingFee > 合計 12000 円なら送料 0 円

src/price.test.ts:

 3 pass
 5 filtered out
 0 fail
 3 expect() calls
Ran 3 tests across 2 files. [4.00ms]

The 5 tests that were not selected are counted as "5 filtered out". With -t 'applyCoupon', only the 2 tests inside the applyCoupon describe ran.

The argument to -t is a regular expression. If no test matches, it results in an error.

text
$ bun test -t 'zzz-no-match'
bun test v1.4.4 (38afee6c8)

src/cart.test.ts:

src/price.test.ts:

error: regex "zzz-no-match" matched 0 tests. Searched 2 files (skipping 8 tests) [5.00ms]

The exit code in this case is also 1. If you mistype a name and no tests run, it is also treated as a failure.

Check test coverage with –coverage

Adding --coverage shows a table of the percentage of functions and lines that the tests reached. No setup is needed.

text
$ bun test --coverage
(テストの結果は省略)
--------------|---------|---------|-------------------
File          | % Funcs | % Lines | Uncovered Line #s
--------------|---------|---------|-------------------
All files     |  100.00 |  100.00 |
 src/cart.ts  |  100.00 |  100.00 | 
 src/price.ts |  100.00 |  100.00 | 
--------------|---------|---------|-------------------

 8 pass
 0 fail
 9 expect() calls
Ran 8 tests across 2 files. [4.00ms]

In these 2 files, functions and lines were both at 100%. If some lines are not reached, their line numbers appear in Uncovered Line #s. The test files themselves are not included in the table. The official coverage page explains how to configure the table output and set a threshold that makes the run fail if coverage falls below it, using bunfig.toml.

bun test misses type errors

bun test runs TypeScript, but it does not check types. To confirm this, I wrote a test that passes the string "300" as price.

ts
import { expect, test } from "bun:test";
import { subtotal } from "./cart";

test("price を文字列で渡す", () => {
  expect(subtotal([{ name: "ノート", price: "300", qty: 2 }])).toBe(600);
});

price is typed as number, so this is wrong in TypeScript. However, this test passed with bun test (1 pass, exit code 0). In JavaScript, "300" * 2 is 600, so the result happened to match.

Point

If you want to catch type errors, use bun test --check. It checks the types of the test file and the files it imports before running the tests.

text
$ bun test --check ./src/type-error.test.ts
bun test v1.4.4 (38afee6c8)
src/type-error.test.ts(5,35): error TS2322: Type 'string' is not assignable to type 'number'.
Found 1 error in 1 file, checked 2 files [18.27ms]

Because a type error was found, no tests ran, and the command ended with exit code 1. After I deleted this test file and ran bun test --check again, all 8 tests ran and passed (34.00ms total).

--check requires the @types/bun package installed in the previous section. A tsconfig.json is not required, though. According to the official documentation, if there is no tsconfig.json, it uses the standard compiler settings and loads @types/bun if it is installed. I ran bun test --check in a folder with neither @types/bun nor tsconfig.json. It reported 4 type errors, including Cannot find module 'bun:test', and no tests ran. The behavior of --check is described in the official bun check page.

With AI agent environment variables, passing test lines are not printed

If you run bun test from an AI agent that sets specific environment variables, such as Claude Code, the output does not show the lines for passing tests, unlike the output above. When one of the environment variables CLAUDECODE=1, REPL_ID=1, or AGENT=1 is set, Bun prints only the failing tests and the summary (official documentation section on AI agents).

text
$ CLAUDECODE=1 bun test
bun test v1.4.4 (38afee6c8)

 8 pass
 0 fail
 9 expect() calls
Ran 8 tests across 2 files. [4.00ms]

Even if the agent's output shows only the summary lines, the tests did run.

​Posted by 86