如何在 Cypress 中调用 REST 并校验响应时间 P95<200ms?
解读
面试官真正想考察的是:
- 你是否理解 P95 响应时间 的统计含义(95% 请求 ≤ 200 ms,而非单次)。
- 能否在 Cypress 单线程、浏览器内运行 的限制下,完成“多次采样 → 排序 → 取 95% 分位 → 断言”的完整闭环。
- 是否具备把“性能指标”纳入自动化门禁的工程化思维,而非只跑功能断言。
国内一线团队普遍把“接口 P95 < 200 ms”写进 DoD(Definition of Done),所以这道题既考编码,也考你对质量门禁的认知深度。
知识点
- cy.request() 只能拿到单次 XHR 的 duration,无法直接给出分位值。
- Cypress 命令队列是串行的,想并发压测需借助 Node 层能力(cy.task 调本地代码)。
- P95 计算:把 N 次响应时间升序排序,取第 Math.ceil(N*0.95) 个元素。
- 性能阈值要随环境浮动:日常流水线 200 ms,预发 300 ms,生产灰度 400 ms,需可配置。
- 失败策略:断言不过时,用 cy.writeFile 落盘原始数组,方便 Jenkins / GitLab CI 下载后二次分析。
答案
下面给出可直接落地到国内 Vue/React 项目流水线(Jenkins + Allure 报告)的完整方案,分三步:采样 → 计算 → 断言。
// cypress/support/task.js —— Node 端计算,避免阻塞浏览器
const axios = require('axios');
module.exports = (on, config) => {
on('task', {
// 入参:{ url, method, headers, body, samples }
async sampling({ url, method, headers, body, samples = 100 }) {
const times = [];
for (let i = 0; i < samples; i++) {
const t0 = Date.now();
await axios({ url, method, headers, data: body, timeout: 5000 });
times.push(Date.now() - t0);
}
times.sort((a, b) => a - b);
const p95 = times[Math.ceil(times.length * 0.95) - 1];
return { p95, array: times }; // 返回给 Cypress
}
});
};
// cypress/integration/api-perf.cy.js
describe('REST 接口 P95 性能门禁', () => {
const cfg = Cypress.env('perf'); // 在 cypress.config.js 或 CI 变量里注入
it('商品详情接口 P95 < 200ms', () => {
cy.task('sampling', {
url: cfg.baseUrl + '/product/123',
method: 'GET',
headers: { 'x-source': 'cypress' },
samples: cfg.samples || 100
}).then(({ p95, array }) => {
// 先落盘,便于失败回溯
cy.writeFile('cypress/outputs/product-p95.json', { p95, array });
// 核心断言
expect(p95).to.be.lessThan(cfg.threshold); // 默认 200
// 顺手把指标打到 Allure 报告
cy.allure().step(`实际 P95=${p95} ms,阈值=${cfg.threshold} ms`);
});
});
});
// cypress.config.js(国内常用配置片段)
const { defineConfig } = require('cypress');
module.exports = defineConfig({
e2e: {
baseUrl: 'https://your-api.xxx.cn',
env: {
perf: {
baseUrl: 'https://your-api.xxx.cn',
samples: 100,
threshold: 200 // 可在 Jenkins 里覆盖:CYPRESS_perf_threshold=180
}
},
setupNodeEvents(on, config) {
return require('./cypress/support/task.js')(on, config);
}
}
});
运行命令(CI 场景):
npx cypress run --env perf.threshold=180 --spec 'cypress/integration/api-perf.cy.js'
若断言失败,日志会打印:
expected 214 to be below 180
同时产物 cypress/outputs/product-p95.json 被归档到 Jenkins,方便下载后做 火焰图或慢查询优化。
拓展思考
- 样本量与置信区间:100 次只是工程折中,金融支付接口建议 400 次以上,并用 t-distribution 计算置信区间,避免偶发抖动误判。
- 持续基线:把每次 P95 写进 InfluxDB,Grafana 出趋势图,红线一旦连续 3 次上涨 >10% 自动@责任人。
- Mock 降级:当后端环境不稳定时,可在 Cypress 前置钩子里先 ping
/health,失败自动降级到 Mock Server,保证门禁脚本不因环境拖累而红。 - 并行采样:若接口允许,可在 task 里用 Promise.allSettled 并发 10 线程,缩短流水线耗时;但要注意 QPS 限流,避免把预发环境打挂。
- 与混沌结合:在采样前注入 Chaos Mesh 网络延迟 50 ms,验证 P95 仍 < 200 ms,才算真正“面向故障设计”。
掌握以上思路,你不仅能在面试中给出可落地的代码,还能把“性能门禁”讲到监控、告警、混沌一体化的高度,稳稳拿下国内大厂的 Cypress 岗位。