Cypress+TypeScript报错:Interception类型无body属性及测试卡顿
问题解决步骤
1. 修正TypeScript类型错误
你直接访问response.body是错误的,cy.wait('@startApplication')返回的Interception对象中,响应体嵌套在response属性里,需要调整为interception.response?.body(用可选链避免空值报错)。
2. 解决测试卡住问题
测试一直加载是因为cy.wait('@startApplication')没等到对应的POST请求——你漏了触发点击操作的代码,必须先执行点击动作,才能触发目标接口请求。
修正后的完整代码
// 拦截POST请求并设置别名 cy.intercept("POST", "**/application").as("startApplication"); // 执行点击操作,触发接口请求(替换成你页面中实际的点击元素选择器) cy.get("button#start-application").click(); // 等待请求完成,提取applicationId并设置别名 cy.wait("@startApplication").then((interception) => { // 用可选链处理response可能为undefined的情况,避免报错 const applicationId = interception.response?.body?.applicationId; if (applicationId) { cy.wrap(applicationId).as("applicationId"); } else { throw new Error("未成功获取到applicationId"); } }); // 后续使用别名调用其他接口的示例 cy.get("@applicationId").then((id) => { cy.request({ method: "GET", url: `/applications/${id}` }); });
额外TypeScript提示
如果IDE仍有类型提示问题,可以给interception添加类型断言:
cy.wait("@startApplication").then((interception: Cypress.Interception) => { // ... 你的代码 });
或者在项目的cypress/support/index.ts中导入Cypress类型定义,确保IDE正确识别:
import "cypress";
内容的提问来源于stack exchange,提问作者hower89
相关产品推荐
相关产品推荐

