14

90% of my tests need to do one task before start so I made beforeEach function that works perfect.

Rest 10% need to do something else before start.

Is in Cypress some way to do beforeEach except some tests?

Dominik Skála
  • 793
  • 4
  • 12
  • 30

2 Answers2

18

No, but you can do some tricks with it. For example:

describe('describe 1', function(){
  beforeEach(function(){
  })
  it('test 1', function(){
  })
  it('test 2', function(){
  })
})

describe('describe 2', function(){
  beforeEach(function(){
  })
  it('test 3', function(){
  })
})

This way you still have your tests clustered in 1 file, but by separating them to several describe()'s you can separate the beforeEach()

Mr. J.
  • 3,499
  • 1
  • 11
  • 25
6

As of cypress version 8.2.0 and above, you can use the Cypress.currentTest object to check which test is running every time.

describe('describe 1', () => {

    beforeEach(() => {
        switch(Cypress.currentTest.title) {
             case 'test 3 - i am not so usual':
             // case 'test 4 - not so usual too': (or any other test title)
                  cy.yourCustomCommand()
                  // or let your special test to take control...below
             break;
             default:
                 // do as usual
                 cy.yourStandardCommand()
             break;
        }
    })
    
     it('usual test 1', () => {})
    
     it('usual test 2', () => {})

     it('test 3 - i am not so usual', () => {
          cy.letMeDoMyStaff()
          // ...
     })
})

Docs: https://docs.cypress.io/api/cypress-api/currenttest

Chris Harris
  • 61
  • 1
  • 2