What is the advantage of Cypress commands over vanilla functions?

Viewed 142

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('my@email.com', '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('my@email.com', '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?

2 Answers

Don't make everything a custom command https://docs.cypress.io/api/cypress-api/custom-commands#Best-Practices JS function is great for grouping cy commands and preferable due to it 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. Also don't be forget cypress provide API for overwriting existing commands not for only creating new commands.

Yes you are right! The goal is to write cleaner code and availability. With custom commands you can basically write the function in the form of a cypress command and also you don't have to write an import statement in the tests suites. Hence your test suite files remain uniform and cleaner.

Related