Hesham Saleh
Hesham Saleh

Reputation: 352

How to skip a cypress test in beforeeach hook?

I want to skip and allow tests in the before each hook as follows

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`, () => {

});

In the place of [How?] I tried using the following:

  1. cy.skipOn(true) from the cypress skip-test plugin but apparently it skips the beforeEach hook not the test itself.
  2. this.skip() but apparently this is not a valid function. Also, if I changed the beforeEach from an arrow function expression, the skip function works but it skips the whole suite and not just the desired test case.

Any ideas?

Upvotes: 4

Views: 3201

Answers (1)

Fody
Fody

Reputation: 31862

Change the function type from arrow function to regular function, then you can use the built-in Mocha skip() method.

beforeEach(function() {
  if (condition) {
    this.skip()
  }
})

Your code sample will look like this:

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`, () => {

});

Or use the Mocha context you already use for test title

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

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

  if (ctx.currentTest.title === 'Skip this') {
    ctx.skip()
  }
});

enter image description here


afterEach()

If you have an afterEach() hook, the this.skip() call does not stop it running for the skipped test.

You should check the condition inside that hook also,

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

  ...  // code that should not run for skipped tests.
})

Upvotes: 8

Related Questions