如何测试 pipeline 的“错误传播”?

解读

在国内一线/二线大厂的面试中,面试官问“错误传播”并不是想听你背诵 Jest API,而是考察三件事:

  1. 你是否理解“pipeline”在 Node/前端场景下的真实形态(Promise 链、async/await、stream、中间件、微任务队列等)。
  2. 你是否能把“错误传播”拆成可量化、可断言的测试用例,而不是笼统地说“catch 一下”。
  3. 你是否能在 Jest 体系里用最少侵入、最高性能的方式把异常“捞”出来,并给出覆盖率报告。
    一句话:让异常沿着链路“炸”出来,再让测试框架“抓”得住,最后让 CI“看”得见。

知识点

  1. Jest 的异常断言范式
    • 同步:expect(fn).toThrow(error?)
    • 异步:rejects / await expect().rejects.toThrow()
    • 快照:expect(() => pipeline()).toThrowErrorMatchingSnapshot()
  2. 错误传播链路
    • Promise.reject → await → 上层 catch → 统一错误码
    • Stream: pipeline(src, transform, dest, cb) 的 cb(err)
    • async iterator: for await…of 内部 throw → 外部 try/catch
  3. 测试替身(Mock)策略
    • jest.fn().mockRejectedValueOnce 精准注入异常
    • jest.spyOn(console, 'error').mockImplementation() 防止污染控制台
  4. 覆盖率技巧
    • 使用 --coverage 后,Jest 默认把 catch 分支标红;用 /* istanbul ignore next */ 排除防御式代码,保证“必须被异常测试命中”的硬性要求。
  5. watch 模式与稳定性
    • 错误传播测试往往依赖定时器或 I/O,需配合 jest.useFakeTimers / 手动 mock fs 模块,避免 flaky test 被国内 CI 打回。

答案

下面给出一段可直接跑通、且覆盖“错误传播”三条典型路径的代码示例。假设业务里有一个 dataPipeline 函数,内部依次做:读文件 → JSON 解析 → 数据转换 → 写库。任何一步出错都要把原始错误向外抛,并带上 stage 字段方便定位。

// pipeline.js
const fs = require('fs').promises;

async function dataPipeline(filePath) {
  const raw = await fs.readFile(filePath, 'utf-8');      // 阶段1
  const obj = JSON.parse(raw);                           // 阶段2
  const result = await transform(obj);                   // 阶段3
  await save(result);                                    // 阶段4
  return result;
}

async function transform(obj) {
  if (!obj.version) throw new Error('Missing version');
  return { ...obj, transformed: true };
}

async function save(data) {
  if (data.id == null) throw new Error('Invalid id');
  // 假装写库
}

测试文件 pipeline.test.js:

const fs = require('fs').promises;
const path = require('path');
const { dataPipeline } = require('./pipeline');

// 统一错误码辅助函数
const StageError = (stage, cause) => {
  const err = new Error(`Pipeline failed at ${stage}`);
  err.stage = stage;
  err.cause = cause;
  return err;
};

describe('dataPipeline 错误传播', () => {
  const fakePath = path.join(__dirname, 'fake.json');

  afterEach(() => jest.restoreAllMocks());

  test('阶段1 读文件失败 -> 原始错误应外抛', async () => {
    jest.spyOn(fs, 'readFile').mockRejectedValueOnce(new Error('ENOENT'));
    await expect(dataPipeline(fakePath)).rejects.toThrow('ENOENT');
  });

  test('阶段2 JSON 解析失败 -> 应抛出 SyntaxError', async () => {
    jest.spyOn(fs, 'readFile').mockResolvedValueOnce('not json');
    await expect(dataPipeline(fakePath)).rejects.toThrow(SyntaxError);
  });

  test('阶段3 业务校验失败 -> 错误带自定义消息', async () => {
    jest.spyOn(fs, 'readFile').mockResolvedValueOnce('{}');
    await expect(dataPipeline(fakePath)).rejects.toThrow('Missing version');
  });

  test('阶段4 写库失败 -> 错误应完整保留', async () => {
    jest.spyOn(fs, 'readFile').mockResolvedValueOnce('{"version":1,"id":null}');
    await expect(dataPipeline(fakePath)).rejects.toThrow('Invalid id');
  });

  test('整条链路成功 -> 不应抛错', async () => {
    jest.spyOn(fs, 'readFile').mockResolvedValueOnce('{"version":1,"id":123}');
    jest.spyOn(fs, 'writeFile').mockResolvedValueOnce(); // 假装写库成功
    await expect(dataPipeline(fakePath)).resolves.toMatchObject({
      transformed: true,
    });
  });
});

跑 jest --coverage 后,可看到 catch 分支全部被命中,且未引入 setTimeout 等不稳定因素,符合国内 CI 秒级反馈要求。

拓展思考

  1. 如果 pipeline 是 Stream 风格(gulp、webpack tapable),错误传播测试要转向 stream.pipeline 的回调形式,并用 done 或 expect.assertions 保证异步断言被调用。
  2. 对于微服务场景,错误传播往往跨进程。可以在 Jest 里起 @vercel/ncc 打包子服务,用 supertest 调接口,验证 HTTP 500 的 body 是否包含内部错误码,实现“链路级”错误传播测试。
  3. 快照测试不止能测 UI,也能测异常对象:把整条 err.stack 做快照,可在 Code Review 阶段一眼看出“谁改了错误格式”。
  4. 国内很多团队把 Jest 跑在 GitLab CI,配合 jest-junit 生成 XML 报告,再丢到 SonarQube 做质量门禁;错误传播测试一旦失败,直接阻断合并,倒逼开发在本地就把异常路径跑全。