如何在Cypress的beforeEach钩子中跳过指定测试用例?
如何在Cypress的beforeEach钩子中跳过指定测试用例
需求是在beforeEach钩子中判断测试用例标题,仅跳过指定测试、允许其他测试执行,现有代码如下:
beforeEach(() =>{ if(Cypress.mocha.getRunner().suite.ctx.currentTest.title === `Skip this`){ // 仅跳过第一个测试用例,运行第二个测试用例 [该如何实现?] } }); it(`Skip this`, () => { }); it(`Don't skip this`, () => { });
尝试过两种方法但均存在问题:
- 使用Cypress skip-test插件的
cy.skipOn(true):仅跳过beforeEach钩子,测试用例本身仍会执行 - 使用
this.skip():箭头函数中无效;改为非箭头函数后生效,但会跳过整个测试套件而非单个测试用例
可行解决方案
你可以直接操作Mocha测试对象的skip()方法实现需求,无需依赖额外插件,具体修改如下:
beforeEach(function() { const currentTest = Cypress.mocha.getRunner().suite.ctx.currentTest; if (currentTest.title === 'Skip this') { currentTest.skip(); // 调用当前测试用例自身的skip方法 } }); it(`Skip this`, () => { // 此测试用例会被跳过 }); it(`Don't skip this`, () => { // 此测试用例会正常执行 });
逻辑说明
- 将
beforeEach的回调改为普通函数(避免箭头函数绑定外部上下文,确保能正确访问测试相关对象) - 通过
Cypress.mocha.getRunner()获取当前Mocha运行器实例,定位到当前测试用例对象currentTest - 直接调用测试用例对象的
skip()方法,只会标记当前测试为跳过状态,不会影响整个测试套件
如果不需要统一在beforeEach中管理,也可以直接在目标测试用例内判断跳过:
it(`Skip this`, () => { cy.state('test').skip(); // 后续代码不会执行 });
内容的提问来源于stack exchange,提问作者Hesham Saleh
相关产品推荐
相关产品推荐

