javascripttestingcypresscypress-conditional-testing

How to make a chainable ".if...()" command in cypress?


Let's say I have a variable username.

Now, my chainable function wants to check if the username is empty or not.

Before:

if(username !== "") {
   cy.get('#username').type(username)
}

After (Expectation):

cy.get('#username').type(username).ifNotEmpty()        //ifNotEmpty will be my chainable func

So my question is Is this even possible? If yes, then how?


Solution

  • You probably just want to make a .type() variation

    Cypress.Commands.add('typeIfNotEmpty', { prevSubject: true }, (subject, textToType) => {
      if (textToType) {
       cy.wrap(subject).type(textToType)
      }
      return subject  // allow further chaining
    })
    
    cy.get('#username')
      .typeIfNotEmpty(username)
      .should(...)               // some assertion on '#username' element