如何编写Cypress测试:接口返回200或超时1分钟自动通过
编写满足特定条件的Cypress测试用例
要实现“接口返回200状态码或一分钟内无响应则测试自动通过”的需求,你可以通过拦截接口、自定义超时时间并捕获超时异常的方式来实现,具体代码示例和说明如下:
// 拦截目标接口,替换为你的实际接口路径与请求方法 cy.intercept('GET', '/api/your-target-endpoint').as('targetApi'); // 触发接口请求的操作(比如访问页面、点击按钮等) cy.visit('/your-page-url'); // 等待接口响应,设置超时时间为1分钟(60000毫秒) cy.wait('@targetApi', { timeout: 60000 }) .then((interception) => { // 验证接口返回状态码为200 expect(interception.response.statusCode).to.equal(200); }) .catch((error) => { // 判断是否为超时错误 if (error.message.includes('timed out waiting for request to complete')) { // 超时情况,标记测试通过 cy.log('接口1分钟内无响应,测试通过'); } else { // 其他错误(比如接口返回非200但未超时),抛出错误终止测试 throw error; } });
关键细节说明
- 接口拦截:使用
cy.intercept拦截目标接口并设置别名(@targetApi),方便后续精准等待该接口的响应。 - 自定义超时:通过
cy.wait的timeout参数将超时时间设置为60000毫秒,覆盖Cypress默认的等待超时(默认通常为30000毫秒)。 - 异常处理:利用
.catch捕获cy.wait的超时异常,通过错误信息判断是否为超时场景,若是则通过日志标记测试通过;其他类型的错误(比如接口返回4xx/5xx且未超时)则正常抛出,确保测试逻辑严谨。
如果需要在多个测试用例中复用该逻辑,可以将其封装为自定义命令,比如在cypress/support/commands.js中添加:
Cypress.Commands.add('waitForApiOrTimeout', (method, apiUrl, timeout = 60000) => { cy.intercept(method, apiUrl).as('apiWait'); cy.wait('@apiWait', { timeout }) .then((interception) => { expect(interception.response.statusCode).to.equal(200); }) .catch((error) => { if (error.message.includes('timed out waiting for request')) { cy.log('接口超时,测试通过'); } else { throw error; } }); });
之后在测试用例中直接调用:
cy.visit('/your-page-url'); cy.waitForApiOrTimeout('GET', '/api/your-target-endpoint');
内容的提问来源于stack exchange,提问作者Tomasz Wojciechowski
相关产品推荐
相关产品推荐

