Search code examples
cypress

What is the advantage of Cypress commands over vanilla functions?


It is known that in Cypress we can define custom commands in the commands.js file, with that syntax:

Cypress.Commands.add('login', (email, pw) => {})
Cypress.Commands.overwrite('visit', (orig, url, options) => {})

These commands will then become available across all our tests and can be used from the cy object.

cy.login('[email protected]', '123456')
cy.visit('www.stackoverflow.com', 'www.google.com', { redirect: true })

But I don't get the gist of it. What is the point of doing that when you could just write a regular function?

function login(email, pw) { /* ... */ }

login('[email protected]', '123456')

The only advantage I see is making the function available everywhere without having to export/import it, but you can do that with globals as well. Is that it, or am I missing something?


Solution

  • 1. Don't make everything a custom command.
    Don't forget: Cypress provides an API for overwriting existing commands, not only for creating new commands.

    JS functions are great for grouping cy commands and preferable due to it's simplicity and readability.

    There’s no reason to add this level of complexity when you’re only wrapping a couple of commands only for avoiding Export/Import.

    2. Don't overcomplicate things. A good test automation framework will be is easily understandable, readable and maintainable. Try not to overcomplicate things and create too many abstractions. When in doubt, Always use a JS function.

    Check this out: https://docs.cypress.io/api/cypress-api/custom-commands#Best-Practices