For AI agents: the complete documentation index is available at https://rstest.rs/zh/llms.txt, the full documentation bundle is available at https://rstest.rs/zh/llms-full.txt, and this page is available as Markdown at https://rstest.rs/zh/guide/basic/snapshot.md.
close
  • 简体中文
  • 快照测试

    快照测试会将值序列化并与已保存的参考快照进行比对。预期内的改动可以更新快照,意外的差异则会让测试失败。

    基本用法

    创建快照

    使用 toMatchSnapshot() 将值的序列化结果写入外部 .snap 文件并比对:

    import { expect, test } from '@rstest/core';
    
    test('component snapshot', () => {
      const user = { name: 'Alice', age: 25 };
      expect(user).toMatchSnapshot();
    });

    默认情况下,Rstest 会生成以 // Rstest Snapshot v1 开头的 .snap 文件:

    // Rstest Snapshot v1
    
    exports[`component snapshot 1`] = `
    {
      "age": 25,
      "name": "Alice",
    }
    `;

    内联快照

    对于简短的输出,可以使用 toMatchInlineSnapshot() 将快照直接写在测试文件内:

    import { expect, test } from '@rstest/core';
    
    test('inline snapshot', () => {
      const message = 'Hello World';
      expect(message).toMatchInlineSnapshot(`"Hello World"`);
    });

    错误快照

    使用 toThrowErrorMatchingSnapshot() 或 toThrowErrorMatchingInlineSnapshot() 为函数抛出的错误(或配合 rejects 为 rejected Promise)生成快照:

    import { expect, test } from '@rstest/core';
    
    test('error snapshot', () => {
      const fail = () => {
        throw new Error('Invalid input');
      };
      expect(fail).toThrowErrorMatchingInlineSnapshot(`[Error: Invalid input]`);
    });

    属性匹配器

    如果对象包含 ID、时间戳等动态字段,可以向 toMatchSnapshot() 或 toMatchInlineSnapshot() 的第一个参数传入属性匹配器对象:

    import { expect, test } from '@rstest/core';
    
    test('dynamic fields', () => {
      const user = { id: Math.random(), name: 'Alice', createdAt: new Date() };
      expect(user).toMatchSnapshot({
        id: expect.any(Number),
        createdAt: expect.any(Date),
      });
    });

    文件快照

    使用 toMatchFileSnapshot(filepath) 将较大的输出或特定格式文件(如 HTML、CSS、JSON)保存为独立快照文件。与 toMatchSnapshot() 不同,toMatchFileSnapshot() 是异步方法,必须使用 await:

    import { expect, test } from '@rstest/core';
    
    test('file snapshot', async () => {
      const result = renderHTML(h('div', { class: 'foo' }));
      await expect(result).toMatchFileSnapshot('./basic.output.html');
    });
    Note

    快照匹配器不支持 .not。调用 expect(value).not.toMatchSnapshot()(或任何带 .not 的快照匹配器)会抛出错误。

    配置选项

    • update:控制是否更新已有快照并清理过期快照(默认值:false)。
    • snapshotFormat:传递给 pretty-format 的序列化格式选项(默认值:{ printShadowRoot: false })。
    • resolveSnapshotPath:自定义 .snap 文件的存储路径。

    更新快照

    默认配置(update: false)下,本地会自动写入新增快照(存在 process.env.CI 时禁用),不匹配则报错。需要更新变更的快照并删除过期快照时,可运行 npx rstest -u、配置 update: true,或在交互式 watch 模式下按 u,详见 update。

    序列化输出

    通过 expect.addSnapshotSerializer 注册自定义序列化器,用于脱敏敏感信息、规范化路径或格式化自定义对象:

    import { expect, test } from '@rstest/core';
    
    expect.addSnapshotSerializer({
      test: (val) => typeof val === 'string' && val.startsWith('secret:'),
      print: () => '***MASKED***',
    });
    
    test('masked secret', () => {
      expect('secret:123').toMatchSnapshot();
    });

    如果快照中包含本地文件系统路径,可以使用 path-serializer 将绝对路径转换为相对项目根目录的路径,保证跨环境结果一致:

    import path from 'node:path';
    import { expect, test } from '@rstest/core';
    import { createSnapshotSerializer } from 'path-serializer';
    
    expect.addSnapshotSerializer(
      createSnapshotSerializer({
        root: path.join(import.meta.dirname, '..'),
      }),
    );
    
    test('serialized snapshot', () => {
      const filePath = path.join(import.meta.dirname, '../data/file.txt');
      expect({ filePath }).toMatchSnapshot();
      // before: "/path/to/repo/examples/node/data/file.txt"
      // after: "<ROOT>/examples/node/data/file.txt"
    });

    快照输出路径

    默认情况下,.snap 文件保存在与测试文件同级的 __snapshots__ 目录中。如需自定义存储路径,请配置 resolveSnapshotPath。

    最佳实践

    • 保持快照聚焦:只序列化与当前断言相关的字段,时间戳、随机 ID 等易变字段用属性匹配器或自定义序列化器处理。
    • 为多个快照命名:同一测试内有多个快照时,传入有区分度的名称:
    test('component state changes', () => {
      const component = new MyComponent();
    
      expect(component.initialState).toMatchSnapshot('initial state');
    
      component.update();
      expect(component.updatedState).toMatchSnapshot('updated state');
    });
    • 更新前审查 diff:运行 -u 前先确认差异是否符合预期;简短输出优先使用内联快照,重构测试时及时清理过期快照。