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

Cypress命令行运行测试报错:Cannot read properties of undefined (reading '_currentRetry')

Cypress CLI运行测试时_currentRetry未定义错误的解决办法

问题场景

使用run_tests.cy.js作为入口文件,通过单个it块引入多个测试文件:

describe('Run tests', () => {
    it('Run all tests', () =>{
        require('../path/to/test_1.cy.js');
        require('../path/to/test_2.cy.js');
        require('../path/to/test_3.cy.js');
        require('../path/to/test_4.cy.js');
        require('../path/to/test_5.cy.js');
        require('../path/to/test_6.cy.js');
        require('../path/to/test_7.cy.js');
    })
})

package.json配置了自定义运行脚本:

"cy:run:test": "cypress run --browser chromium --config baseUrl=https://google.com/ --spec './cypress/e2e/path/to/run_tests.cy.js'",

通过npx cypress open手动运行正常,但执行npm run cy:run:test时出现错误:

Cannot read properties of undefined (reading '_currentRetry')
TypeError: Cannot read properties of undefined (reading '_currentRetry')
    at E.<anonymous> (<embedded>:4644:13577)
    at E.parseArgs (<embedded>:4644:16785)
    at E.emit (<embedded>:4644:16602)
    at Object.onMocha (<embedded>:4691:427158)
    at p.<anonymous> (<embedded>:4691:68249)
    at p.emit (node:events:527:28)
    at p.emitUntyped (<embedded>:4402:84346)
    at <embedded>:4402:91863
    at process.processTicksAndRejections (node:internal/process/task_queues:78:11)

解决办法

1. 直接通过CLI参数指定要运行的测试文件

这是最稳妥的方式,避免单个测试块引入其他测试文件导致的上下文冲突。修改package.json中的脚本,将--spec参数指向所有目标测试文件:

// 方式1:使用通配符匹配所有测试文件
"cy:run:test": "cypress run --browser chromium --config baseUrl=https://google.com/ --spec './cypress/e2e/path/to/test_*.cy.js'",

// 方式2:明确列出所有测试文件路径
"cy:run:test": "cypress run --browser chromium --config baseUrl=https://google.com/ --spec './cypress/e2e/path/to/test_1.cy.js','./cypress/e2e/path/to/test_2.cy.js','./cypress/e2e/path/to/test_3.cy.js','./cypress/e2e/path/to/test_4.cy.js','./cypress/e2e/path/to/test_5.cy.js','./cypress/e2e/path/to/test_6.cy.js','./cypress/e2e/path/to/test_7.cy.js'",

2. 调整入口文件的测试结构(不推荐)

如果必须保留入口文件,不要将require放在单个it块内,而是直接在describe块下引入:

describe('Run tests', () => {
    require('../path/to/test_1.cy.js');
    require('../path/to/test_2.cy.js');
    require('../path/to/test_3.cy.js');
    require('../path/to/test_4.cy.js');
    require('../path/to/test_5.cy.js');
    require('../path/to/test_6.cy.js');
    require('../path/to/test_7.cy.js');
})

但这种方式仍可能存在上下文兼容问题,优先推荐第一种方案。

错误原因

Cypress CLI运行时依赖Mocha的测试上下文管理,在单个it块中引入多个独立测试文件会破坏Mocha的内部上下文状态,导致_currentRetry这类内部属性无法正确绑定到测试实例上。而Cypress GUI模式(cypress open)的上下文处理逻辑与CLI不同,因此不会触发该错误。

额外排查点

  • 检查Cypress版本,升级到最新稳定版,避免版本兼容问题;
  • 确认所有测试文件无语法错误或未正确导出的测试逻辑;
  • 排查是否存在自定义Mocha钩子(如beforeEach、afterEach)干扰测试上下文。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 19:17:41