'Setting global variables, functions in cypress

I wonder if its possible to set up for example variable with function for login on global level in cypress. So I could for example on start of every test write " login; " and then just continue from when I am already inside app.

Same thing for " logout;" function.



Solution 1:[1]

You can achieve this by using cypress custom commands. Here is the doc - https://docs.cypress.io/api/cypress-api/custom-commands.html

You can create custom commands under cypress/support/commands.js

An example from the cypress doc of how a login function can look like:

Cypress.Commands.add('typeLogin', (user) => {
  cy.get('input[name=email]')
    .type(user.email)

  cy.get('input[name=password]')
    .type(user.password)
})

Now in the tests, you use the above custom command as:

cy.typeLogin({ email: '[email protected]', password: 'Secret1' })

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 Alapan Das