Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress command vs JS function

Tags:

cypress

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();
like image 937
mbatchkarov Avatar asked Apr 30 '26 16:04

mbatchkarov


2 Answers

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"))
        })
      }
like image 200
Mikhail Bolotov Avatar answered May 03 '26 18:05

Mikhail Bolotov


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

like image 22
light Avatar answered May 03 '26 17:05

light



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!