日本語

How to Run the Same Bun Test with Different Values Using test.each

​​Bun​Testing,TypeScript

Passing a table of values to test.each in bun test creates one test per row, all running the same body. You only list the inputs and expected results, and the test body is written once.

This is the approach for writing a test that checks many inputs the same way (also called a parameterized test or table-driven test), such as input validation for postal codes or phone numbers. I go through, in order, how to pass the table, how to put values into test names, and a way of writing names that garbles the display with Japanese labels, using the output from my test environment.

Note

My test environment was Ubuntu 24.04 (x86_64) with Bun 1.4.4. For type checking I used @types/bun 1.4.4 and TypeScript 5.9.3. I did not test the template-literal table syntax from Jest, combinations with other modifiers such as test.concurrent.each, or Windows and macOS. In the output, the paths of my test environment are replaced with /path/to/.

Pass an array table to get one test per row

As an example, I wrote normalizePostalCode in postal.ts, a function that formats a postal code as 123-4567. It returns null for input that cannot be read as a postal code.

ts
// Format the postal code as "123-4567". Return null if it can't be read as a postal code.
export function normalizePostalCode(input: string): string | null {
  const digits = input.trim().replace(/-/g, "");
  if (!/^\d{7}$/.test(digits)) return null;
  return `${digits.slice(0, 3)}-${digits.slice(3)}`;
}

In the test file postal.test.ts, I pass an array of [input, expected] pairs to test.each. The function that test.each(table) returns takes the test name and the test body.

ts
import { expect, test } from "bun:test";
import { normalizePostalCode } from "./postal";

test.each([
  ["1234567", "123-4567"],
  ["123-4567", "123-4567"],
  [" 123-4567 ", "123-4567"],
  ["123-4567", "123-4567"],
  ["123-456", null],
  ["abc-defg", null],
])("%p は %p になる", (input, expected) => {
  expect(normalizePostalCode(input)).toBe(expected);
});

As described in the official documentation on how arguments are passed, when a row is an array, each element is passed to the body as a separate argument. Here the first goes into input and the second into expected. The %p in the test name is replaced by the row's values, in order.

Running bun test turned the six rows into six tests.

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

postal.test.ts:
(pass) "1234567" は "123-4567" になる [0.16ms]
(pass) "123-4567" は "123-4567" になる [0.06ms]
(pass) " 123-4567 " は "123-4567" になる
 7 |   [" 123-4567 ", "123-4567"],
 8 |   ["123-4567", "123-4567"],
 9 |   ["123-456", null],
10 |   ["abc-defg", null],
11 | ])("%p は %p になる", (input, expected) => {
12 |   expect(normalizePostalCode(input)).toBe(expected);
                                          ^
error: expect(received).toBe(expected)

Expected: "123-4567"
Received: null

      at <anonymous> (/path/to/postal-app/postal.test.ts:12:38)
(fail) "123-4567" は "123-4567" になる [0.20ms]
(pass) "123-456" は null になる
(pass) "abc-defg" は null になる

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

Only the row entered in full-width characters failed. The error's line number points to the expect in the body (line 12). To see which input failed, look at the test name after (fail). That is why I put the input value into the name.

I fixed it by converting full-width digits and hyphens to half-width with normalize("NFKC") before processing.

ts
// Format the postal code as "123-4567". Return null if it can't be read as a postal code.
// Full-width digits and hyphens are normalized to half-width with NFKC normalization before processing.
export function normalizePostalCode(input: string): string | null {
  const digits = input.normalize("NFKC").trim().replace(/-/g, "");
  if (!/^\d{7}$/.test(digits)) return null;
  return `${digits.slice(0, 3)}-${digits.slice(3)}`;
}
text
$ bun test postal.test.ts
bun test v1.4.4 (38afee6c8)

postal.test.ts:
(pass) "1234567" は "123-4567" になる [0.14ms]
(pass) "123-4567" は "123-4567" になる [0.01ms]
(pass) " 123-4567 " は "123-4567" になる
(pass) "123-4567" は "123-4567" になる [0.05ms]
(pass) "123-456" は null になる
(pass) "abc-defg" は null になる

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

Format specifiers that put values into test names

The official table of format specifiers lists %p, %s, %d, %i, %f, %j, %o, %# (the zero-based row index), and %% (a single % character).

I used %p in the example above because %s did not put null into the name. When I changed the name to "%s は %s になる" and ran it, the two rows with null kept the %s.

text
$ bun test postal-s.test.ts
bun test v1.4.4 (38afee6c8)

postal-s.test.ts:
(pass) 1234567 は 123-4567 になる [0.16ms]
(pass) 123-4567 は 123-4567 になる [0.08ms]
(pass)  123-4567  は 123-4567 になる
(pass) 123-4567 は 123-4567 になる [0.07ms]
(pass) 123-456 は %s になる
(pass) abc-defg は %s になる

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

With %s, a name also makes it hard to tell that an input has spaces around it. %p wraps strings in quotes, as in " 123-4567 ", so a padded input is easy to spot.

I also checked what each of the other specifiers puts in the name. I used eight values, "12.5円", 42, 3.75, -3.75, the object { name: "Alice", tags: ["a"] }, null, [1, 2], and true, and changed the specifier one at a time.

Specifier Values inserted into the name Values left as the specifier
%s Strings only (12.5円) Numbers, objects, null, arrays, true
%d, %f Numbers only (42, 3.75, -3.75) Strings, objects, null, arrays, true
%i Integers only (42) Everything else, including 3.75 and -3.75
%p Everything (strings as "12.5円", objects across multiple lines) None
%j, %o Everything (single-line JSON such as {"name":"Alice","tags":["a"]}) None

%d inserted 3.75 as a decimal, while %i left 3.75 as %i. Because %p inserts objects across multiple lines, the test name is displayed over several lines.

text
(pass) %p > → {
  name: "Alice",
  tags: [ "a" ],
}
(pass) %j > → {"name":"Alice","tags":["a"]}
Point

When a row mixes null or numbers in with strings, use %p instead of %s. If you want an object on a single line, %j works well.

Write %% when you want a literal % in the name

A % character in a name, as in "tax rate 10%", also needs care. I tried three ways of writing it.

ts
test.each([[10]])("税率 10% のとき %d 円", () => {});
test.each([[10]])("税率 10%% のとき %d 円", () => {});
test.each([[10]])("税率 %d% のとき", () => {});
text
(pass) 税率 10 のとき 10 円 [0.02ms]
(pass) 税率 10% のとき 10 円 [0.02ms]
(pass) 税率 10% のとき

In the first, only the % was removed, so the name became "tax rate 10 when 10 yen" with the % gone. In the second, written as %%, one % remains. In the third, a % after all the values had been used stayed as it was. When you want a % character before a value-inserting specifier, write %%.

Object tables and $name

If a row is an object, the body receives the row object as a single argument. In the test name, writing $ followed by a property name, such as $label, inserts that property's value.

However, when Japanese characters directly follow a $name, the name gets garbled. In the next test, full-width parentheses come right after $label and $input.

ts
import { expect, test } from "bun:test";
import { normalizePostalCode } from "./postal";

test.each([
  { label: "ハイフンなし", input: "1234567", expected: "123-4567" },
  { label: "全角", input: "123-4567", expected: "123-4567" },
  { label: "6桁しかない", input: "123-456", expected: null },
])("$label($input)は $expected になる", ({ input, expected }) => {
  expect(normalizePostalCode(input)).toBe(expected);
});
text
$ bun test postal-object.test.ts
bun test v1.4.4 (38afee6c8)

postal-object.test.ts:
(pass) $label�$input�は 123-4567 になる [0.17ms]
(pass) $label�$input�は 123-4567 になる [0.08ms]
(pass) $label�$input�は $expectedになる

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

The values for $label and $input were not inserted, and the trailing parentheses became �, a character that cannot be read. The first and second rows got the same name, so you cannot tell which row a test belongs to. In the third row, where expected is null, $expected stayed as it was and the space after it was lost.

I then tried changing only the character that comes right after $name:

text
(pass) 全角 のとき [0.04ms]
(pass) $label�とき
(pass) $label�次 [0.03ms]
(pass) (全角)
(pass) ($label�
(pass) 120 円
(pass) $price�
(pass) $valueになる

From top to bottom, these were written as $label のとき, $labelのとき, $label、次, ($label), ($label), $price 円, $price円, and $value になる (where value is null). When a space or a half-width bracket follows, the value was inserted. When a Japanese character or a full-width symbol follows, it was garbled. For $value with a null value, the name kept $value even when a space followed, and that space was lost. Looking at the $labelのとき row in bytes, one of the three bytes of the hiragana character for "no" was dropped, leaving a sequence that cannot be read as text.

The official documentation for format specifiers does not describe this behavior. Put a space or a half-width symbol directly after $name.

I changed the name to put : and a space after $name, and I limited the inserted values to string properties.

ts
test.each([
  { label: "ハイフンなし", input: "1234567", expected: "123-4567" },
  { label: "全角", input: "123-4567", expected: "123-4567" },
  { label: "6桁しかない", input: "123-456", expected: null },
])("$label: $input", ({ input, expected }) => {
  expect(normalizePostalCode(input)).toBe(expected);
});
text
$ bun test postal-object.test.ts
bun test v1.4.4 (38afee6c8)

postal-object.test.ts:
(pass) ハイフンなし: 1234567 [0.25ms]
(pass) 全角: 123-4567 [0.07ms]
(pass) 6桁しかない: 123-456

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

Narrow down by name to run a single row

You can narrow tests made by test.each by their name after values are inserted, using -t (--test-name-pattern). -t is the option that selects tests by name, as described in the official documentation on filtering.

text
$ bun test postal-object.test.ts -t 全角
bun test v1.4.4 (38afee6c8)

postal-object.test.ts:
(pass) 全角: 123-4567 [0.21ms]

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

Only the full-width case, which I set as the label, ran, and the other two were filtered out. When I ran the same -t 全角 against the version with the garbled names, which used full-width parentheses, it failed with regex "全角" matched 0 tests and no tests ran. Building the names correctly also matters for filtering.

Repeat a group of tests with describe.each

When you want to check several things for each input, use describe.each. A describe group is created for each row, and the test blocks inside can use the row's values.

ts
import { describe, expect, test } from "bun:test";
import { normalizePostalCode } from "./postal";

describe.each([
  ["ハイフンあり", "123-4567"],
  ["ハイフンなし", "1234567"],
  ["全角", "123-4567"],
])("%s で入力したとき", (_label, input) => {
  test("123-4567 の形にそろう", () => {
    expect(normalizePostalCode(input)).toBe("123-4567");
  });

  test("前後に空白があってもそろう", () => {
    expect(normalizePostalCode(`  ${input}  `)).toBe("123-4567");
  });
});
text
$ bun test postal-describe.test.ts
bun test v1.4.4 (38afee6c8)

postal-describe.test.ts:
(pass) ハイフンあり で入力したとき > 123-4567 の形にそろう [0.12ms]
(pass) ハイフンあり で入力したとき > 前後に空白があってもそろう [0.02ms]
(pass) ハイフンなし で入力したとき > 123-4567 の形にそろう
(pass) ハイフンなし で入力したとき > 前後に空白があってもそろう
(pass) 全角 で入力したとき > 123-4567 の形にそろう [0.04ms]
(pass) 全角 で入力したとき > 前後に空白があってもそろう

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

Three rows times two tests gave six tests. Running with -t '全角 で入力したとき' ran only the two tests in the full-width group and reported 4 filtered out.

Don't declare more body arguments than the row has values

Be careful about the number of arguments the body accepts. The next test has only two values per row, but the body declares a third argument, label.

ts
test.each([
  ["1234567", "123-4567"],
])("%p は %p になる", (input, expected, label) => {
  expect(normalizePostalCode(input)).toBe(expected);
});
text
$ bun test done.test.ts
bun test v1.4.4 (38afee6c8)

done.test.ts:
(fail) "1234567" は "123-4567" になる [5000.05ms]
  ^ this test timed out after 5000ms, before its done callback was called. If a done callback was not intended, remove the last parameter from the test callback function

 0 pass
 1 fail
 1 expect() calls
Ran 1 test across 1 file. [5.00s]

The expect passed, but the test failed after waiting five seconds. The last argument, which received no value from the row, was treated as the done function that signals the end of the test. The error message also advises removing the last argument if done was not meant to be used. The official documentation on async tests also states that if the body takes done, the test does not finish until it is called. When you add or remove columns in the table, match the number of body arguments to it.

With TypeScript, the table determines the argument types

In an environment with @types/bun installed, the types of the body arguments are determined by the contents of the table. To confirm that input is only ever a string, I deliberately assigned it to a number variable and ran the type check.

ts
test.each([
  ["1234567", "123-4567"],
  ["123-456", null],
])("%p は %p になる", (input, expected) => {
  const n: number = input; // Deliberately put the value into a number to check the type of input.
  expect(normalizePostalCode(input)).toBe(expected);
});
text
$ bunx tsc --noEmit --strict --types bun types.test.ts
types.test.ts(8,9): error TS2322: Type 'string' is not assignable to type 'number'.

input was treated as string, which caused a type error. Without writing a type in the table, the type check on the body's arguments still works.

​Posted by 86