如何跳过 beforeeach 钩子中的 cypress 测试?

Hes*_*eer 2 cypress

我想跳过并允许在每个钩子之前进行测试,如下所示

beforeEach(() =>{
  if(Cypress.mocha.getRunner().suite.ctx.currentTest.title === `Skip this`){
     // skip the first test case only but run the second one [How?]
  }
});

it(`Skip this`, () => {

});

it(`Don't skip this`, () => {

});
Run Code Online (Sandbox Code Playgroud)

我尝试使用以下内容代替[如何?]:

  1. cy.skipOn(true)来自 cypress Skip-test插件,但显然它跳过了 beforeEach 钩子而不是测试本身。
  2. this.skip()但显然这不是一个有效的函数。另外,如果我从箭头函数表达式更改 beforeEach,则跳过函数可以工作,但它会跳过整个套件,而不仅仅是所需的测试用例。

有任何想法吗?

Fod*_*ody 6

将函数类型从箭头函数改为常规函数,就可以使用内置的Mochaskip()方法了。

beforeEach(function() {
  if (condition) {
    this.skip()
  }
})
Run Code Online (Sandbox Code Playgroud)

您的代码示例将如下所示:

beforeEach(function() {     // NOTE regular function

  if (Cypress.mocha.getRunner().suite.ctx.currentTest.title === 'Skip this') {
    this.skip()
  }
});

it(`Skip this`, () => {

});

it(`Don't skip this`, () => {

});
Run Code Online (Sandbox Code Playgroud)

或者使用您已用于测试标题的Mocha 上下文

beforeEach(() => {        // NOTE arrow function is allowed

  const ctx = Cypress.mocha.getRunner().suite.ctx

  if (ctx.currentTest.title === 'Skip this') {
    ctx.skip()
  }
});
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述


每个之后()

如果您有一个afterEach()钩子,则该this.skip()调用不会停止它为跳过的测试运行。

您还应该检查该钩子内部的状况,

afterEach(function() {
  if (condition) return;

  ...  // code that should not run for skipped tests.
})
Run Code Online (Sandbox Code Playgroud)