Cypress如何用intercept仅监听响应体含特定值的GET请求
Cypress intercept 按响应体过滤等待请求解决方案
你可以通过以下三种方式实现仅等待响应体符合要求的请求返回,无需依赖URL参数匹配:
方式1:递归等待原生实现(无第三方依赖,兼容所有Cypress版本)
通过递归调用cy.wait匹配下一个请求,直到命中目标响应体:
// 拦截所有符合路径规则的GET请求 cy.intercept("GET", "/api/users/*").as("userRequests") // 此处填写触发请求的业务操作,比如页面刷新、点击提交按钮等 // ...... // 定义递归等待逻辑 const waitForAliceResponse = () => { cy.wait("@userRequests").then((interceptRes) => { // 若当前请求不符合要求,继续等待下一个 if (interceptRes.response.body.name !== "Alice") { return waitForAliceResponse() } // 命中目标请求后做后续断言/操作 expect(interceptRes.response.statusCode).to.eq(200) expect(interceptRes.response.body.description).to.eq("Created by Cypress") }) } // 执行等待逻辑 waitForAliceResponse()
如果接口返回的是字符串格式的JSON,需要先做解析再判断:JSON.parse(interceptRes.response.body).name === "Alice"
方式2:Cypress v12.7.0+ 原生过滤写法(最简洁)
较新版本Cypress已内置请求过滤配置,可直接在cy.wait中指定响应匹配规则:
cy.intercept("GET", "/api/users/*").as("userRequests") // 此处填写触发请求的业务操作 // ...... // 直接等待命中响应体规则的请求返回 cy.wait("@userRequests", { timeout: 10000, // 可自定义超时时间 matchCase: { response: { body: { name: "Alice" } } } }).then((aliceRes) => { // 后续业务逻辑 expect(aliceRes.response.statusCode).to.eq(200) })
方式3:通过变量标记匹配请求(适合多条件复杂判断场景)
适合需要对请求/响应做多维度复杂判断的场景:
let targetIntercept = null cy.intercept("GET", "/api/users/*", (req) => { req.continue((res) => { // 自定义匹配逻辑,满足条件则标记 if (res.body.name === "Alice" && res.statusCode === 200) { targetIntercept = {req, res} } }) }) // 此处填写触发请求的业务操作 // ...... // 配合cypress-wait-until插件等待标记生效,若为Cypress 12+也可自定义重试逻辑 cy.waitUntil(() => targetIntercept !== null, { timeout: 10000 }).then(() => { expect(targetIntercept.res.body.description).to.eq("Created by Cypress") })
内容的提问来源于stack exchange,提问作者ggonmar
相关产品推荐
相关产品推荐

