如何对 fileUpload 标量做“流”断言?

解读

在国内前端面试中,GraphQL 的 Upload 标量(通常由 graphql-upload 或 apollo-server 提供)会被当成一个“可读流”交给 resolver。
面试官真正想考察的是:

  1. 你能否把“流”这种异步可迭代对象当成普通值来做断言;
  2. 会不会用 Jest 提供的异步匹配器(resolves / rejects / .then)以及自定义非对称匹配器;
  3. 是否理解流的生命周期(必须消费完再关闭,否则测试进程会挂起)。
    一句话:把“流”当成黑盒,用 Jest 的异步断言能力验证它的内容、长度、MIME 类型,而不是自己去写一堆 on('data') 回调。

知识点

  • Jest 异步断言:return promise、async/await、resolves/rejects
  • 非对称匹配器 expect.any(Function)、expect.stringMatching、expect.objectContaining
  • 自定义匹配器 expect.extend({ toBeValidUploadStream })
  • 流消费:streamConsumers.text / buffer (Node 16+) 或自己用 chunks 累加
  • 测试隔离:afterEach 销毁流,防止句柄泄漏导致 Jest 挂起
  • 国内常用场景:React + Ant Design Upload 组件、GraphQL 文件上传、Node BFF 层对接阿里云 OSS 前先做单测

答案

// fileUpload.test.js
import { Readable } from 'stream';
import { text } from 'stream/consumers';
import { GraphQLUpload } from 'graphql-upload';

// 自定义非对称匹配器:只关心流能不能被读成指定文本
const toBeStreamText = async (received, expected) => {
  const content = await text(received);
  if (content !== expected) {
    return {
      pass: false,
      message: () => `expected stream to contain "${expected}", but got "${content}"`,
    };
  }
  return { pass: true };
};

expect.extend({ toBeStreamText });

describe('fileUpload 标量流断言', () => {
  it('应该正确消费 Upload 流并断言内容', async () => {
    // 1. 造一个假的 Upload 对象,符合 graphql-upload 规范
    const upload = {
      filename: '简历.pdf',
      mimetype: 'application/pdf',
      encoding: '7bit',
      createReadStream: () => Readable.from('hello 世界'),
    };

    // 2. 把 Upload 标量序列化成真正的流(resolver 里就是这么拿到的)
    const stream = await upload.createReadStream();

    // 3. 用 Jest 异步断言一次性消费
    await expect(text(stream)).resolves.toBe('hello 世界');

    // 4. 如果想复用流,需要重新 createReadStream,因为流只能读一次
    const stream2 = upload.createReadStream();
    await expect(stream2).toBeStreamText('hello 世界');
  });

  it('应该断言文件类型与大小', async () => {
    const buffer = Buffer.from('mock pdf binary');
    const upload = {
      filename: '证书.pdf',
      mimetype: 'application/pdf',
      encoding: 'binary',
      createReadStream: () => Readable.from(buffer),
    };

    const stream = upload.createReadStream();
    const content = await text(stream);

    // 用普通断言即可,因为 content 已经是同步值
    expect(content.length).toBe(16);
    expect(upload.mimetype).toMatch(/^application\/pdf$/);
  });
});

跑 npm test -- fileUpload.test.js,全部通过即证明“流”断言写对了。
注意:

  1. 一定要在测试里把流读完,否则 Jest 会报 “Jest has exited with 1 open handle”;
  2. 如果项目 Node 版本低于 16,没有 stream/consumers,可以用 new Promise 包一层 stream.on('data') 自己累加 chunks,思路完全一致。

拓展思考

  1. 多文件并发上传:使用 Promise.all(uploads.map(u => text(u.createReadStream()))) 结合 expect.arrayContaining 做批量断言。
  2. 大文件分片:把流包成 fs.createReadStream(path, { highWaterMark: 64 * 1024 }),在测试里用 toBeStreamText 断言前 64 KB 的魔数头,验证分片逻辑。
  3. 自定义 Jest 环境:如果团队用 jsdom 环境跑前端单测,需要把 Readable 换成 Blob + FileReader,断言思路不变,都是“异步消费 → 异步匹配器”。
  4. 覆盖率:流分支(异常、空文件、超大文件)要写独立用例,确保 npx jest --coverage 达到团队门禁(国内大厂通常要求 90%)。