SunAndMoon91
SunAndMoon91

Reputation: 81

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.

Upvotes: 3

Views: 5266

Answers (2)

Aladin Spaz
Aladin Spaz

Reputation: 9718

You can achieve login persistence using the cy.session() command.

From the example documentation,

beforeEach(() => {
  cy.session('login', () => {
    cy.visit('/login')
    cy.get('[data-test=name]').type(name)
    cy.get('[data-test=password]').type('s3cr3t')
    cy.get('form').contains('Log In').click()
    cy.url().should('contain', '/login-successful')
  })
})

Put this code into cypress/support/e2e.js to ensure it runs before every test in every spec (when using the cacheAcrossSpecs=true option in configuration).

NOTE the login only performs once, cy.session() manages the stored credentials automatically for you.

Upvotes: 4

Alapan Das
Alapan Das

Reputation: 18650

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' })

Upvotes: 3

Related Questions