mbatchkarov
mbatchkarov

Reputation: 16039

Cypress command vs JS function

The Cypress documentation suggests that commands are the right way to reuse fragments of code, e.g.

Cypress.Commands.add("logout", () => {
  cy.get("[data-cy=profile-picture]").click();
  cy.contains("Logout").click();
});

cy.logout();

For simple cases like this, why would I use a command over a plain JS function (and all the nice IDE assistance that comes with it). What are the drawbacks of rewriting the above snippet as

export function logout(){
  cy.get("[data-cy=profile-picture]").click();
  cy.contains("Logout").click();
}

// and now somewhere in a test
logout();

Upvotes: 10

Views: 5435

Answers (2)

light
light

Reputation: 21

Commands are for behavior that is needed across all tests. For example, cy.setup or cy.login. Otherwise, use functions. See official docs: https://docs.cypress.io/api/cypress-api/custom-commands#1-Don-t-make-everything-a-custom-command

Upvotes: 1

Mikhail Bolotov
Mikhail Bolotov

Reputation: 1104

Based on my experience with Cypress (one year project and several hundred test cases), I can say that a plan JS function is great for grouping cy commands.

From my point of view, a custom cy command may be really useful only if it is incorporated into the chain processing (utilizes the subject parameter or returns a Chainable to be used further in the chain). Otherwise, a plain JS function is preferable due to it simplicity and full IDE support (unless you're using an additional plugin).

If you for any reason need to do something inside the cypress loop, you can always wrap you code by cy.then() in a plain JS function:

      function myFunction() {
        cy.then(() => {
          console.log(("I'm inside the Cypress event loop"))
        })
      }

Upvotes: 6

Related Questions