如何测试订阅 resolver 的“心跳”?

解读

在国内 GraphQL 项目里,订阅(Subscription)常用于实时推送行情、IM 消息或 IoT 设备心跳。
“心跳”本质是一个按固定频率吐数据的流(AsyncIterator),面试官想看三件事:

  1. 能不能把异步流切成可断言的“时间片”;
  2. 会不会用 Jest 的 Mock 能力替换掉真实定时器,保证 CI 稳定;
  3. 覆盖率能不能抓到异常分支(网络断、流异常、取消订阅)。
    一句话:把“时间”变成“数据”,再按同步方式断言。

知识点

  • Jest 假定时器(useFakeTimers + advanceTimersByTime)
  • AsyncIterator 的 next/return/throw 协议
  • graphql-subscriptions 的 PubSub 抽象与异步触发
  • 订阅 resolver 的 resolve/filter 钩子
  • 流完成与取消(return 方法被调用的时机)
  • 异常分支覆盖(reject 后是否触发 onError)
  • CI 并发下用 fakeTimers 避免 setInterval 漂移

答案

代码示例:用 graphql-ws + graphql-subscriptions 实现一个每 1000 ms 吐一次 { beat: number } 的心跳订阅,测试用 Jest 28+ 编写。

// heartbeat.resolver.js
import { PubSub } from 'graphql-subscriptions';
const pubsub = new PubSub();
let beat = 0;

export const heartbeatResolver = {
  Subscription: {
    heartbeat: {
      subscribe: () => pubsub.asyncIterator('HEARTBEAT'),
    },
  },
};

// 生产代码里用 setInterval 推事件
export function startBeating() {
  setInterval(() => {
    pubsub.publish('HEARTBEAT', { heartbeat: { beat: ++beat } });
  }, 1000);
}
// heartbeat.resolver.test.js
import { useFakeTimers, advanceTimersByTime, clearAllTimers } from 'jest';
import { execute, subscribe, parse } from 'graphql';
import { makeExecutableSchema } from '@graphql-tools/schema';
import { heartbeatResolver } from '../heartbeat.resolver';
import { startBeating } from '../heartbeat.resolver';

const typeDefs = `
  type Heartbeat { beat: Int! }
  type Subscription { heartbeat: Heartbeat! }
  schema { subscription: Subscription }
`;

const schema = makeExecutableSchema({
  typeDefs,
  resolvers: heartbeatResolver,
});

describe('心跳订阅', () => {
  beforeEach(() => {
    jest.useFakeTimers();
  });

  afterEach(() => {
    jest.clearAllTimers();
    jest.useRealTimers();
  });

  it('应该在 3 秒内吐出 3 个心跳', async () => {
    startBeating(); // 启动生产定时器
    const asyncIter = await subscribe({
      schema,
      document: parse('subscription { heartbeat { beat } }'),
    });

    const values = [];
    // 把异步流拉出来
    const pull = async () => {
      const { value, done } = await asyncIter.next();
      if (!done) values.push(value.data.heartbeat.beat);
    };

    // 时间切片断言
    advanceTimersByTime(1000);
    await pull();
    expect(values).toEqual([1]);

    advanceTimersByTime(1000);
    await pull();
    expect(values).toEqual([1, 2]);

    advanceTimersByTime(1000);
    await pull();
    expect(values).toEqual([1, 2, 3]);

    // 取消订阅
    await asyncIter.return();
    expect(asyncIter.return).toHaveBeenCalledTimes(1);
  });

  it('当流异常时应该触发 onError 并结束', async () => {
    const asyncIter = await subscribe({
      schema,
      document: parse('subscription { heartbeat { beat } }'),
    });

    // 模拟 PubSub 内部抛错
    asyncIter.throw(new Error('network'));

    await expect(asyncIter.next()).rejects.toThrow('network');
  });
});

要点复盘

  1. 用 useFakeTimers 把 1 秒压成 0 毫秒,CI 零漂移。
  2. 把 AsyncIterator 当生成器,手动调用 next/return,同步断言。
  3. 异常分支用 throw 模拟,确保 onError 钩子被覆盖。
  4. 记得 clearAllTimers 防止用例间串扰。

拓展思考

  1. 如果心跳频率降到 100 ms,测试用例爆炸怎么办?
    用“窗口采样”策略:只抽第 0、10、20 个包,断言时间戳差值,其余用 Jest 的 toBeCloseTo 做容差。
  2. 微服务场景下心跳跨进程,PubSub 用 Redis。
    测试时把 graphql-redis-subscriptions 换成内存版 Mock,保证单测无外部依赖,集成测试再连真实 Redis。
  3. 客户端断网重连,GraphQL 会重新发起订阅。
    用 Jest 的 spyOn 监听 subscribe 调用次数,结合 advanceTimersByTime 模拟断网 30 秒后重连,断言重连后 beat 序号连续。
  4. 高并发下心跳流合并(beat 合并成 batch)。
    测试策略:把 advanceTimersByTime(5000) 一次推进,断言返回数组长度与 batchSize 一致,且数组内 beat 单调递增。