You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress+TypeScript中mocha属性报错及state读取失败问题求助

Cypress+TypeScript+Cucumber 获取测试场景结果的问题及解决过程

我在Cypress+TypeScript+Cucumber环境下,尝试在After钩子中获取每个测试场景的结果,使用了以下代码:

Cypress.mocha.getRunner().suite.ctx.currentTest.state

但触发了TypeScript错误:"Property 'mocha' does not exist on type Cypress & CyEventEmitter"。虽然Mocha是Cypress默认测试框架,理论上Cypress.mocha应能在After钩子中正常工作,但实际出现了类型问题。

我的tsconfig.json配置如下:

{
  "compilerOptions": {
    "target": "es2016",                                
    "lib": ["es6"],                                
    "module": "commonjs",                                
    "types": ["cypress","cypress-xpath","node"],                                 
    "resolveJsonModule": true,                        
    "esModuleInterop": true,                              
    "strict": true,                                      
    "forceConsistentCasingInFileNames": true,  
    "skipLibCheck": true 
  }
}

第一步解决:TypeScript类型错误

通过类型断言(Cypress as any).mocha.getRunner().suite...解决了上述类型不存在的错误,但随即遇到新问题:"Cannot read properties of undefined (reading 'state')"。

最终解决方案

将After钩子替换为afterEach后,Cannot read properties of undefined (reading 'state')问题得到解决,完整解决方案可参考评论区。

环境版本:Cypress 12、Node.js 18、cypress-cucumber-preprocessor 4.3

内容的提问来源于stack exchange,提问作者Sagarika

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 18:13:13