Skip to content

Snapshot 测试 for 配置对象

简单 约 25 分钟

你将构建什么

配置 generator 模块那个 produces app 配置对象, 使用 snapshot 测试那个 detect 任何 unintended 更改到 配置结构.

学习目标

  • 创建配置 generator 函数
  • 编写 snapshot 测试 using toMatchSnapshot()
  • 理解当 snapshots 更新 and 如何 review 它们
  • 学习到 use inline snapshots 使用 toMatchInlineSnapshot()
  • 练习 reviewing snapshot diffs

前置要求

  • 已完成项目 1 or equivalent Jest experience
  • 理解的 JavaScript 对象

步骤

  1. 1

    创建配置 generator

    创建 configGenerator.js 那个 produces 配置对象.

    代码
    function generateConfig(env) {
      return {
        env,
        api: {
          baseUrl: env === 'production' ? 'https://api.example.com' : 'http://localhost:3000',
          timeout: env === 'production' ? 5000 : 30000,
        },
        features: {
          darkMode: true,
          analytics: env === 'production',
        },
      };
    }
    module.exports = { generateConfig };

    预期结果

    configGenerator.js 是创建.

  2. 2

    编写 snapshot 测试

    创建 configGenerator.测试.js 使用 snapshot 测试 for 不同环境.

    代码
    const { generateConfig } = require('./configGenerator');
    
    test('development config snapshot', () => {
      expect(generateConfig('development')).toMatchSnapshot();
    });
    
    test('production config snapshot', () => {
      expect(generateConfig('production')).toMatchSnapshot();
    });

    预期结果

    测试通过 and __snapshots__ directory 是创建使用 .snap files.

  3. 3

    Review snapshot file

    打开 generated .snap file and review 保存 snapshots. 理解那个这些 represent expected 输出.

    预期结果

    你理解 snapshot file 格式 and 内容.

  4. 4

    测试 snapshot 更改 detection

    Temporarily 修改配置 generator (e.g., 更改 darkMode 到假). 运行测试 — 它们应该失败, showing diff. 然后 revert 更改.

    预期结果

    测试失败 showing 精确 diff, 然后通过之后 reverting.

  5. 5

    添加边界测试用例

    为测试套件添加边界值用例:空数组、零值、最大值、null/undefined。边界用例是最容易出错的地方,必须显式覆盖。

    代码
    describe("boundary cases", () => {
      it("handles empty array", () => {
        expect(func([])).toEqual([]);
      });
    
      it("handles zero", () => {
        expect(func(0)).toBe(0);
      });
    
      it("handles null", () => {
        expect(() => func(null)).toThrow();
      });
    
      it("handles max value", () => {
        expect(func(Number.MAX_SAFE_INTEGER)).toBeDefined();
      });
    });

    预期结果

    所有边界用例通过,无未捕获异常。

自己动手试试

你学到了什么

你学习如何 snapshot 测试工作: 首先运行 captures 输出, subsequent 运行 compare 针对它. Snapshots 是 powerful for detecting unexpected 更改 in 复杂对象, 但你 必须 review diffs carefully 之前更新它们.

相关资源

相关课程

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误

← 返回主题