当需要模拟订阅时,如何基于 `graphql-ws` 创建虚拟 WebSocket 服务器?

解读

国内面试中,GraphQL 订阅(Subscription)的“可运行 Demo”是高频考点。
面试官真正想确认的是:

  1. 你能否脱离后端,独立搭一条“假长连接”给 Apollo Client 做集成测试;
  2. 是否理解 graphql-ws 协议与 Apollo 链路(Link)的衔接点;
  3. 能否在 Node 端用最小成本启动一个“干净、可脚本化、可断言”的 WebSocket 服务,而不是把生产代码搬过来。

一句话:要“快、轻、无依赖、能发能收”,还要能随时注入异常场景。

知识点

  • graphql-ws 子协议(graphql-transport-ws)与旧 subscriptions-transport-ws 的区别
  • useServer 与 makeServer 的用法:把 WebSocket 裸连接升级为 GraphQL 会话
  • 虚拟 Schema 的两种写法:① buildSchema 字符串 ② makeExecutableSchema(可插 resolver)
  • 可迭代异步生成器(AsyncIterable)作为订阅源,符合 GraphQL 规范
  • 端口“0”技巧:让 OS 随机分配端口,避免 CI 冲突
  • 与 Apollo Client 的 GraphQLWsLink 对接时,connectionParams 的透传与鉴权模拟
  • 常用异常注入:① 立即抛错 ② 心跳超时 ③ 脏数据帧 ④ 随机断链

答案

下面给出一段“复制即可跑”的虚拟服务器代码,兼顾单元测试与 Storybook 演示场景。
依赖仅三项:graphql, graphql-ws, ws,无数据库、无框架。

npm i -D graphql graphql-ws ws
// mock-graphql-ws-server.js
import { buildSchema } from 'graphql';
import { useServer } from 'graphql-ws/lib/use/ws';
import { WebSocketServer } from 'ws';

const schema = buildSchema(`
  type Query { hello: String }
  type Subscription {
    counter(target: Int = 5): Int!
    message(room: String!): String!
  }
`);

// 根解析器
const roots = {
  subscription: {
    counter: async function* ({ target }) {
      for (let i = 1; i <= target; i++) {
        yield { counter: i };
        await new Promise(r => setTimeout(r, 300)); // 可控节拍
      }
    },
    message: async function* ({ room }) {
      let seq = 0;
      while (true) {
        yield { message: `[${room}] 第${++seq}条广播` };
        await new Promise(r => setTimeout(r, 1000));
      }
    },
  },
};

export function startVirtualServer(port = 0) {
  const wss = new WebSocketServer({ port, path: '/graphql' });
  const server = useServer(
    {
      schema,
      roots,
      // 统一错误包装,方便前端捕获
      onError: (ctx, msg, errors) => {
        console.error('[虚拟WS] 错误:', errors);
        return errors; // 返回给客户端
      },
      // 鉴权钩子:测试时可直接 return true
      onConnect: ctx => {
        const token = ctx.connectionParams?.authToken;
        if (token === 'bad') throw new Error('虚拟鉴权失败');
        return true; // 通过
      },
    },
    wss,
  );

  const { port: actualPort } = wss.address();
  console.log(`✅ 虚拟 WebSocket 已就绪 → ws://localhost:${actualPort}/graphql`);
  return {
    url: `ws://localhost:${actualPort}/graphql`,
    close: () => {
      server.dispose();
      wss.close();
    },
  };
}

// CLI 直接启动
if (import.meta.url === `file://${process.argv[1]}`) {
  startVirtualServer(4000);
}

前端侧 Apollo Client 连接示例(React 场景):

import { GraphQLWsLink } from '@apollo/client/link/subscriptions';
import { createClient } from 'graphql-ws';

const wsLink = new GraphQLWsLink(
  createClient({
    url: 'ws://localhost:4000/graphql',
    connectionParams: () => ({ authToken: 'demo-token' }),
  }),
);

至此,虚拟服务器已能:

  1. 按节拍推送 counter 序列,供 UI 做累加动画;
  2. 持续广播 message,供聊天室组件测试;
  3. 通过 onError 与 onConnect 注入鉴权失败、随机异常等场景;
  4. 一键 close(),在 Jest 的 afterAll 中回收,避免端口占用。

拓展思考

  1. 多客户端隔离:利用 graphql-ws 的 context 给每个连接生成 UUID,并在订阅 resolver 里按 ID 过滤事件,实现“单测互不干扰”。
  2. 压力模拟:在生成器里 yield 大量数据(如 10k/s),结合 Chrome DevTools 的“帧率”面板,验证 Apollo Client 的 back-pressure 与缓存淘汰策略。
  3. 网络抖动:在 ws 实例上包一层 throttle 或随机 close(),测试 Apollo 的自动重连与 reconnect: true 表现。
  4. 同构场景:把同一套虚拟服务器挂到 GitHub Actions 的 services 字段,配合 Playwright 做端到端截图测试,实现“无后端”的 MR 门禁。