'How to make a chainable 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 1:[1]

You can add a custom Cypress command to achieve this. These are called child commands. More information here.

Cypress.Commands.add('ifNotEmpty', { prevSubject: true }, (subject) => {
  // code
})

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 agoff