Search code examples
cypress

Adding multiple it() functions to cypress custom command


Is adding multiple it() functions within a custom command possible? These functions are the most common tasks that we run and are journey-based. I would like the idea to have a custom command that will include all these three it() functions with associated content

it('add a new pet', function () {
  cy.createPet(param1, param2)
})

it('give pet attributes', function () {
  cy.setPetAttributes(param3)
})

it('set owner and delivery date for pet', function () {
  cy.setOwnerAndDeliveryDate(param4, param5)
})

Solution

  • If you try to run any cy.* command outside of a test (it()) you will get an error

    CypressError
    The following error originated from your test code, not from Cypress.
    Cannot call cy.get() outside a running test.

    If you try to call a test inside another test (via a custom command), it will not run the inner tests.

    One approach is to create a function to run the tests,

    function runTests() {
      it('test1', () => {
        ...
      })
       it('test2', () => {
        ...
      })
    })
    
    ...
    
    runTests()
    

    but you must call it outside of any other tests (at the top level of the spec).

    Another option is to have these tests in a spec file, then require() that spec at the top of any other specs they precede.

    I presume by "journey-based" that you are turning off test isolation to preserve page state between tests,

    context('pet journey', () => {
    
      require('./pet-setup.cy.js')   // tests that create pet etc
    
      it('deliver pet', () => {
        ...
      })
    
      ...
    })