日本語

How to Write Snapshot Tests with bun test in Bun

​​Bun​Testing,TypeScript

When you want to check a large object returned by a function, or a string shown on screen, all at once instead of writing one expect per field, snapshot testing works well. In Bun's bun test, calling toMatchSnapshot() is enough. The result of the first run is saved to a file, and from the second run on, the output is compared against that saved content. Snapshot tests suit regression tests, which check whether the output has changed before and after a refactoring.

In my test environment, depending on how I passed --update-snapshots, the snapshots of other tests were sometimes deleted. I include those results below.

Note

The test environment was Ubuntu 24.04 (x86_64) with Bun 1.4.4. The folder contained only TypeScript files, with no package.json or config files. I did not test snapshots of components such as React, --parallel, or Windows and macOS. For Bun's official documentation, I checked the source files at the tag used for testing (bun-v1.4.4) on GitHub, and the links point there.

Saving the result to a file with toMatchSnapshot()

The function under test is summarize, which builds line items and totals from the cart contents (src/order.ts).

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

// Build line items and totals from the cart contents
export function summarize(items: Item[]) {
  const subtotal = items.reduce((sum, i) => sum + i.price * i.qty, 0);
  const tax = Math.floor(subtotal * 0.1);
  return {
    lines: items.map((i) => `${i.name} × ${i.qty}  ${i.price * i.qty}円`),
    subtotal,
    tax,
    total: subtotal + tax,
  };
}

In the test, pass the value you want to check to expect() and call toMatchSnapshot(). You don't write the expected value. The second test calls it twice within a single test.

ts
import { describe, expect, test } from "bun:test";
import { summarize } from "./order";

describe("summarize", () => {
  test("2つの商品の明細と合計", () => {
    const result = summarize([
      { name: "ノート", price: 180, qty: 3 },
      { name: "ボールペン", price: 120, qty: 2 },
    ]);
    expect(result).toMatchSnapshot();
  });

  test("空のカート", () => {
    expect(summarize([])).toMatchSnapshot();
    expect(summarize([]).lines).toMatchSnapshot();
  });
});

On the first bun test run, there is nothing to compare against yet, so every test passes. The summary line shows snapshots: +3 added, meaning three snapshots were saved.

text
$ bun test ./src/order.test.ts
bun test v1.4.4 (38afee6c8)

src/order.test.ts:
(pass) summarize > 2つの商品の明細と合計 [0.72ms]
(pass) summarize > 空のカート [0.10ms]

 2 pass
 0 fail
snapshots: +3 added
 3 expect() calls
Ran 2 tests across 1 file. [5.00ms]

The snapshots are saved to __snapshots__/order.test.ts.snap, created in the same folder as the test file. The contents looked like this.

text
// Bun Snapshot v1, https://bun.sh/docs/test/snapshots

exports[`summarize 2つの商品の明細と合計 1`] = `
{
  "lines": [
    "ノート × 3  540円",
    "ボールペン × 2  240円",
  ],
  "subtotal": 780,
  "tax": 78,
  "total": 858,
}
`;

exports[`summarize 空のカート 1`] = `
{
  "lines": [],
  "subtotal": 0,
  "tax": 0,
  "total": 0,
}
`;

exports[`summarize 空のカート 2`] = `[]`;

Each entry is saved under a name made of the describe name, the test name, and a number showing which toMatchSnapshot() call this is within that test. For 空のカート, the first call became 空のカート 1 and the second became 空のカート 2.

On the second bun test run, the output is compared with the saved content. The summary line changed to 3 snapshots.

text
 2 pass
 0 fail
 3 snapshots, 3 expect() calls
Ran 2 tests across 1 file. [5.00ms]

Commit this .snap file to Git together with the test file. The official documentation's steps for reviewing and committing snapshot changes also run git add on the updated snapshots and commit them.

When the output changes, the test fails with a diff

Next, I changed the format of each line from the "name × quantity" style to a "name (N pcs)" style, with the amount in yen at the end. I rewrote the lines line in src/order.ts as follows.

ts

lines: items.map((i) => `${i.name}(${i.qty}点)${i.price * i.qty}円`),

When I ran bun test again, one test failed, and the diff showed the saved content (-) and the new value (+).

text
$ bun test ./src/order.test.ts
bun test v1.4.4 (38afee6c8)

src/order.test.ts:
(ソースコードの抜粋は省略)
error: expect(received).toMatchSnapshot(expected)

  
  {
    "lines": [
-     "ノート × 3  540円",
-     "ボールペン × 2  240円",
+     "ノート(3点)540円",
+     "ボールペン(2点)240円",
    ],
    "subtotal": 780,
    "tax": 78,
    "total": 858,
  }
  

- Expected  - 2
+ Received  + 2

      at <anonymous> (/path/to/snap-app/src/order.test.ts:10:20)
(fail) summarize > 2つの商品の明細と合計 [0.56ms]
(pass) summarize > 空のカート [0.05ms]

 1 pass
 1 fail
snapshots: 2 passed, 1 failed
 3 expect() calls
Ran 2 tests across 1 file. [4.00ms]

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

Even when a test fails, the .snap file is not rewritten. If the change was intended, run with --update-snapshots (short form -u) to overwrite the saved content with the new values.

text
$ bun test --update-snapshots ./src/order.test.ts
bun test v1.4.4 (38afee6c8)

src/order.test.ts:
(pass) summarize > 2つの商品の明細と合計 [0.50ms]
(pass) summarize > 空のカート [0.04ms]

 2 pass
 0 fail
snapshots: +3 added
 3 expect() calls
Ran 2 tests across 1 file. [4.00ms]

Only one test had changed, but the summary showed +3 added. Comparing the .snap file with diff against the version from before the rewrite, only the two line-item lines had actually changed.

text
$ diff ../old.snap src/__snapshots__/order.test.ts.snap
6,7c6,7
<     "ノート × 3  540円",
<     "ボールペン × 2  240円",
---
>     "ノート(3点)540円",
>     "ボールペン(2点)240円",

Add --update-snapshots only after you have confirmed that the diff is intended. If the change was not what you expected, fix the code rather than the .snap file.

Inline snapshots are written into the test file

For short strings or small arrays, toMatchInlineSnapshot() writes the saved value into the test file itself. You can read the expected value right next to the test without opening another file. To save the message of a thrown error, use toThrowErrorMatchingInlineSnapshot().

I tried this with yen (src/price.ts), a function that puts a thousands separator in an amount.

ts
// Separate the amount every three digits and append the yen suffix
export const yen = (n: number) => `${n.toLocaleString("ja-JP")}円`;

In the test, both toMatchInlineSnapshot() and toThrowErrorMatchingInlineSnapshot() are called with no arguments.

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

test("3桁ごとに区切る", () => {
  expect(yen(1234567)).toMatchInlineSnapshot();
  expect([yen(0), yen(999), yen(1000)]).toMatchInlineSnapshot();
});

test("負の金額はエラー", () => {
  expect(() => {
    throw new Error("金額が負です: -1");
  }).toThrowErrorMatchingInlineSnapshot();
});

After one run of bun test ./src/price.test.ts, both tests passed and the output showed snapshots: +3 added. The test file had been rewritten as follows (diff -u against the file before the run).

diff
 test("3桁ごとに区切る", () => {
-  expect(yen(1234567)).toMatchInlineSnapshot();
-  expect([yen(0), yen(999), yen(1000)]).toMatchInlineSnapshot();
+  expect(yen(1234567)).toMatchInlineSnapshot(`"1,234,567円"`);
+  expect([yen(0), yen(999), yen(1000)]).toMatchInlineSnapshot(`
+    [
+      "0円",
+      "999円",
+      "1,000円",
+    ]
+  `);
 });
 
 test("負の金額はエラー", () => {
   expect(() => {
     throw new Error("金額が負です: -1");
-  }).toThrowErrorMatchingInlineSnapshot();
+  }).toThrowErrorMatchingInlineSnapshot(`"金額が負です: -1"`);
 });

Strings are written inside double quotes, and multi-line values are written with indentation. When I ran it again, both tests passed against the values that had been written.

The official documentation's recommendations on using snapshots advise keeping snapshots small. A snapshot that grows to thousands of lines, such as a whole page, is hard to review when it changes.

For IDs and timestamps that change each run, check only the shape of the value with property matchers

createOrder (src/order-id.ts), which creates an order, returns a different id and creation time on each call.

ts
// Create an order. The id and creation time change on every call
export function createOrder(customer: string) {
  return {
    id: crypto.randomUUID(),
    customer,
    status: "受付",
    createdAt: new Date().toISOString(),
  };
}

I put two tests side by side: a test that snapshots the return value as is (そのまま撮る), and a test that passes property matchers to toMatchSnapshot(). For the fields with matchers, the value is not compared directly. Instead, it is compared with expect.any(String) (must be a string) or expect.stringMatching() (must match a regular expression).

ts
import { expect, test } from "bun:test";
import { createOrder } from "./order-id";

test("そのまま撮る", () => {
  expect(createOrder("山田")).toMatchSnapshot();
});

test("変わる値は型だけを確かめる", () => {
  expect(createOrder("山田")).toMatchSnapshot({
    id: expect.any(String),
    createdAt: expect.stringMatching(/^\d{4}-\d{2}-\d{2}T/),
  });
});

In the .snap file saved on the first run, only the fields given matchers contained Any<String> or StringMatching instead of values.

text
exports[`そのまま撮る 1`] = `
{
  "createdAt": "2026-11-15T08:13:17.186Z",
  "customer": "山田",
  "id": "6d205929-bfa5-4209-bcdd-46aad3155c45",
  "status": "受付",
}
`;

exports[`変わる値は型だけを確かめる 1`] = `
{
  "createdAt": StringMatching /^\\d{4}-\\d{2}-\\d{2}T/,
  "customer": "山田",
  "id": Any<String>,
  "status": "受付",
}
`;

On the second run, the そのまま撮る test failed because id and createdAt differed from the previous run, while the test with matchers passed.

text
$ bun test ./src/order-id.test.ts
(ソースコードの抜粋と集計の行は省略)
error: expect(received).toMatchSnapshot(expected)

  
  {
-   "createdAt": "2026-11-15T08:13:17.186Z",
+   "createdAt": "2026-11-15T08:13:17.195Z",
    "customer": "山田",
-   "id": "6d205929-bfa5-4209-bcdd-46aad3155c45",
+   "id": "0ace7f39-c260-43e7-b409-535f70409013",
    "status": "受付",
  }
  

- Expected  - 2
+ Received  + 2

      at <anonymous> (/path/to/snap-app/src/order-id.test.ts:5:29)
(fail) そのまま撮る [0.63ms]
(pass) 変わる値は型だけを確かめる [0.24ms]

Even in the test with matchers, customer and status are saved as their actual values.

In CI, the test fails instead of creating new snapshots

As above, when you run tests locally, a toMatchSnapshot() with nothing to compare against saves the value and passes. According to the official documentation on updating snapshots, in a CI environment, new snapshots are not written unless --update-snapshots is passed.

I added a test named 1つの商品 to src/order.test.ts, then ran it with the environment variable CI=true set, while the .snap file had no record for it.

text
$ CI=true bun test ./src/order.test.ts
bun test v1.4.4 (38afee6c8)

src/order.test.ts:
(pass) summarize > 2つの商品の明細と合計 [0.63ms]
(pass) summarize > 空のカート [0.05ms]
(ソースコードの抜粋は省略)
error: Snapshot creation is disabled in CI environments unless --update-snapshots is used
To override, set the environment variable CI=false.

Snapshot name: "1つの商品 1"
Received: 
{
  "lines": [
    "消しゴム(1点)80円",
  ],
  "subtotal": 80,
  "tax": 8,
  "total": 88,
}

      at <anonymous> (/path/to/snap-app/src/order.test.ts:20:60)
(fail) 1つの商品 [0.25ms]

 2 pass
 1 fail
 4 snapshots, 4 expect() calls
Ran 3 tests across 1 file. [5.00ms]

The added test failed, and the .snap file was the same as before the run. When I set GITHUB_ACTIONS=true instead of CI, it also failed with the same error. Inline snapshots behaved the same way: with CI=true, they raised the error Inline snapshot creation is disabled in CI environments, and the test file was not rewritten. Even with CI=true still set, adding --update-snapshots wrote the records, and the tests passed.

In CI, where CI=true is set, forgetting to commit a snapshot you created locally makes the build fail like this. When you add a new test, commit the .snap file and any test files that changed along with it.

Renaming a test leaves the old record behind

Snapshots are looked up by name, so when you rename a test, its record is recreated under the new name. I renamed 1つの商品 to 商品が1つ and ran the tests. The output showed snapshots: 3 passed, 1 added, and all tests passed. However, the .snap file still contained the record under the old name.

text
$ grep -n '^exports' src/__snapshots__/order.test.ts.snap
3:exports[`summarize 2つの商品の明細と合計 1`] = `
15:exports[`summarize 空のカート 1`] = `
24:exports[`summarize 空のカート 2`] = `[]`;
26:exports[`1つの商品 1`] = `
37:exports[`商品が1つ 1`] = `

The output gave no warning that an unused record existed. When I ran with --update-snapshots, the whole file was rewritten and the 1つの商品 1 record was removed.

text
$ grep -n '^exports' src/__snapshots__/order.test.ts.snap
3:exports[`summarize 2つの商品の明細と合計 1`] = `
15:exports[`summarize 空のカート 1`] = `
24:exports[`summarize 空のカート 2`] = `[]`;
26:exports[`商品が1つ 1`] = `

Updating with a -t filter deletes records of tests that were not run

Because --update-snapshots rewrites the whole file, it can cause problems when you run only some tests. I selected only 空のカート with -t (an option that filters by test name) and ran with --update-snapshots.

text
$ bun test --update-snapshots -t 空のカート ./src/order.test.ts
bun test v1.4.4 (38afee6c8)

src/order.test.ts:
(pass) summarize > 空のカート [0.35ms]

 1 pass
 2 filtered out
 0 fail
snapshots: +2 added
 2 expect() calls
Ran 1 test across 1 file. [4.00ms]
text
$ grep -n '^exports' src/__snapshots__/order.test.ts.snap
3:exports[`summarize 空のカート 1`] = `
12:exports[`summarize 空のカート 2`] = `[]`;

Next, I ran bun test with no options. The output showed snapshots: 2 passed, 2 added. The two deleted records were recreated from the current results, and the tests passed.

Warning

If you filter with -t and add --update-snapshots, the records of tests excluded by the filter (here, 2つの商品の明細と合計 and 商品が1つ) are removed from the .snap file. If their output changes before the next local run, the test won't fail. Instead, the new output is saved as a new record. When updating, it is safer to run all the tests in the file, then check the changes to .snap with git diff.

​Posted by 86