如何在Cypress API中等待JSON响应出现指定值?
Cypress 等待API返回指定状态的实现方案
需求很明确:重复请求目标API,直到响应里的第一个条目满足activated: true且fileType不等于inprogress。这里提供几种实用的实现方式:
方式一:递归请求检查
直接用cy.request递归调用,每次检查响应是否符合条件,不符合就等待一段时间后再重试:
function waitForActivatedFile() { cy.request('/你的API地址') .then(res => { const targetFile = res.body[0]; // 校验目标状态 if (targetFile.activated && targetFile.fileType !== 'inprogress') { return; // 满足条件,终止循环 } // 间隔1秒后重试,可根据实际调整 cy.wait(1000); waitForActivatedFile(); }); } // 测试中调用该函数 waitForActivatedFile();
注意:如果担心无限等待,可以加个超时计数器,比如超过60秒就抛出错误:
function waitForActivatedFile(maxAttempts = 60) { if (maxAttempts <= 0) { throw new Error('等待文件激活超时'); } cy.request('/你的API地址') .then(res => { const targetFile = res.body[0]; if (targetFile.activated && targetFile.fileType !== 'inprogress') { return; } cy.wait(1000); waitForActivatedFile(maxAttempts - 1); }); }
方式二:结合intercept监听请求
如果是页面自动触发API请求,可以用cy.intercept监听,每次响应后检查状态:
// 监听目标API cy.intercept('GET', '/你的API地址').as('fileStatus'); function checkFileStatus() { cy.wait('@fileStatus').then(interception => { const targetFile = interception.response.body[0]; if (targetFile.activated && targetFile.fileType !== 'inprogress') { return; } cy.wait(1000); // 手动触发一次请求(如果页面不会自动刷新的话) cy.request('/你的API地址'); checkFileStatus(); }); } // 先触发一次初始请求 cy.request('/你的API地址'); checkFileStatus();
方式三:封装自定义命令(推荐)
把逻辑封装成Cypress自定义命令,方便在多个测试用例中复用,还能统一设置超时和间隔:
// 在cypress/support/commands.js中添加 Cypress.Commands.add('waitForFileActivated', (apiUrl, timeout = 60000, interval = 1000) => { const start = Date.now(); function check() { if (Date.now() - start > timeout) { throw new Error(`等待超时,已超过${timeout}ms`); } return cy.request(apiUrl) .then(res => { const targetFile = res.body[0]; if (targetFile.activated && targetFile.fileType !== 'inprogress') { return res; // 返回最终响应,方便后续断言 } return cy.wait(interval).then(check); }); } return check(); }); // 测试中直接调用 cy.waitForFileActivated('/你的API地址') .then(res => { // 可在此添加后续断言 expect(res.body[0].activated).to.be.true; });
内容的提问来源于stack exchange,提问作者Smh
相关产品推荐
相关产品推荐

