如何对 GraphQL 与 REST 混合网关做“协议”快照?
解读
在国内微服务落地场景中,BFF(Backend For Frontend)层往往同时暴露 GraphQL 与 REST 两套入口:老业务沿用 REST,新业务拥抱 GraphQL,网关负责协议转发、聚合与裁剪。面试问“协议快照”,不是让你拍整个响应体,而是验证“网关吐出的协议结构”——字段、类型、枚举、分页格式、错误码——一旦后端重构,只要协议结构没变,前端就能无感升级。因此快照必须:
- 与具体数据解耦(脱敏)
- 同时覆盖 GraphQL 的 Schema 与 REST 的 JSON 结构
- 能在 CI 中 1 秒 diff,失败时给出可读的 break-change 提示
知识点
- Jest 快照机制:expect(value).toMatchSnapshot() 把序列化结果写入 snapshots,下次用同一份测试名做严格相等比对
- 自定义序列化器:snapshotSerializers 可把 GraphQL AST、OpenAPI、Protobuf 等统一转成可读的 JSON 骨架
- 协议无关快照策略:
- GraphQL 侧:对 introspection 结果做“类型裁剪”后快照
- REST 侧:用 json-schema-faker 反向推导 Schema 再快照
- Mock 隔离:nock / MSW 在 Node 层拦截真实后端,保证快照只测网关逻辑
- 快照回归治理:jest -u 按需更新,配合 husky + lint-staged 禁止本地随意 -u,必须在 MR 里 review
答案
下面给出可直接落地的 Jest 方案,分三步:环境隔离、协议采样、快照生成。
- 目录约定
bff-test/
├─ __tests__/
│ ├─ protocol-snapshot.test.js
│ └─ __snapshots__/
├─ serializers/
│ └─ gql-schema.js
└─ mocks/
├─ nock-rest.js
└─ graphql-handler.js
- 安装依赖
pnpm add -D jest msw@latest nock@latest lodash graphql lodash.get
- 自定义 GraphQL 序列化器(serializers/gql-schema.js)
module.exports = {
test(val) {
return val && val.__schema;
},
print(val) {
// 只保留类型名、字段名、是否非空,去掉描述与废弃字段
const clean = (type) => {
if (type.kind === 'NON_NULL') return `${clean(type.ofType)}!`;
if (type.kind === 'LIST') return `[${clean(type.ofType)}]`;
return type.name;
};
const fields = (fields) =>
fields.map((f) => `${f.name}: ${clean(f.type)}`).sort();
const types = val.__schema.types
.filter((t) => !t.name.startsWith('__'))
.map((t) => ({
name: t.name,
kind: t.kind,
fields: t.fields ? fields(t.fields) : null,
}));
return JSON.stringify(types, null, 2);
},
};
- 测试用例(protocol-snapshot.test.js)
import { graphql } from 'msw';
import { setupServer } from 'msw/node';
import nock from 'nock';
import axios from 'axios';
import { printSchema, buildClientSchema } from 'graphql';
import { introspectionQuery } from './introspection-query';
import gqlSchemaSerializer from '../serializers/gql-schema';
expect.addSnapshotSerializer(gqlSchemaSerializer);
const restBase = 'https://gateway.example.com/api';
const gqlEndpoint = 'https://gateway.example.com/graphql';
// 1) 隔离后端
const server = setupServer(
graphql.query('IntrospectionQuery', (req, res, ctx) =>
res(ctx.data(require('../mocks/introspection.json'))),
);
beforeAll(() => {
server.listen({ onUnhandledRequest: 'error' });
nock(restBase)
.get('/v1/user/profile')
.reply(200, require('../mocks/rest-profile.json'));
});
afterAll(() => {
server.close();
nock.cleanAll();
});
describe('协议快照', () => {
it('GraphQL 网关 Schema 应与快照一致', async () => {
const resp = await axios.post(gqlEndpoint, {
query: introspectionQuery,
});
// 用自定义序列化器脱敏
expect(resp.data.data).toMatchSnapshot('gql-schema');
});
it('REST 网关返回结构应与快照一致', async () => {
const { data } = await axios.get(`${restBase}/v1/user/profile`);
// 只保留结构,值用占位符
const mask = (obj) => {
if (Array.isArray(obj)) return obj.map(mask);
if (obj && typeof obj === 'object') {
const masked = {};
for (const [k, v] of Object.entries(obj)) {
masked[k] = typeof v === 'object' ? mask(v) : '{{*}}';
}
return masked;
}
return '{{*}}';
};
expect(mask(data)).toMatchSnapshot('rest-profile-structure');
});
});
- 运行与更新
jest --ci --updateSnapshot # 本地禁止,仅 CI 可更新
若后端新增字段,CI 会失败,开发者在 MR 里 review 后执行 jest --updateSnapshot 并再次 push,保证所有 break-change 可追踪。
拓展思考
- 多环境快照:在 nightly 流水线里对预发网关跑同一份测试,对比生产快照,提前发现“预发 Schema 超前”问题
- 契约驱动:把快照结果转成 JSON Schema 上传到内部契约中心(如阿里 Nacos、腾讯 TARS),供前端 TypeScript 自动生成类型,实现“后端一改,前端立刻红”
- 性能快照:对网关做压力测试时,把 p99 延迟、错误码分布一起快照,防止“结构没变但性能劣化”
- 灰度策略:利用 Jest 的 testNamePattern 只跑增量接口的快照,结合 Node 的 worker_threads 并行采样,10 秒完成千级别字段校验,满足国内大厂日迭代节奏