Bun

快照

快照测试保存一个值的输出,并将其与未来的测试运行进行比较。这对于 UI 组件、复杂对象或任何需要保持一致的输出特别有用。

基本快照

快照测试使用 ` .toMatchSnapshot() ` 匹配器编写。

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

test("snap", () => {
  expect("foo").toMatchSnapshot();
});

第一次运行此测试时,`expect` 的参数将被序列化并写入测试文件旁边 `__snapshots__` 目录中的一个特殊快照文件。在未来的运行中,该参数将与磁盘上的快照进行比较。快照可以使用以下命令重新生成:

bun test --update-snapshots

内联快照

对于较小的值,你可以使用 ` .toMatchInlineSnapshot() ` 进行内联快照。这些快照直接存储在你的测试文件中。

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

test("inline snapshot", () => {
  // First run: snapshot will be inserted automatically
  expect({ hello: "world" }).toMatchInlineSnapshot();

  // After first run, the test file will be updated to:
  // expect({ hello: "world" }).toMatchInlineSnapshot(`
  //   {
  //     "hello": "world",
  //   }
  // `);
});

当你运行测试时,Bun 会自动用生成的快照字符串更新测试文件本身。这使得测试更具可移植性且更容易理解,因为预期的输出就在测试旁边。

使用内联快照

  1. 使用 ` .toMatchInlineSnapshot() ` 编写你的测试
  2. 运行一次测试
  3. Bun 自动用快照更新你的测试文件
  4. 在随后的运行中,该值将与内联快照进行比较。

内联快照对于小而简单的值特别有用,因为它有助于在测试文件中直接看到预期的输出。

错误快照

你还可以使用 ` .toThrowErrorMatchingSnapshot() ` 和 ` .toThrowErrorMatchingInlineSnapshot() ` 对错误消息进行快照。

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

test("error snapshot", () => {
  expect(() => {
    throw new Error("Something went wrong");
  }).toThrowErrorMatchingSnapshot();

  expect(() => {
    throw new Error("Another error");
  }).toThrowErrorMatchingInlineSnapshot();
});