最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Setting global variables, functions in cypress - Stack Overflow

programmeradmin4浏览0评论

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.

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.

Share Improve this question edited May 7, 2022 at 2:14 bad_coder 13k20 gold badges55 silver badges88 bronze badges asked Aug 11, 2020 at 13:13 SunAndMoon91SunAndMoon91 811 silver badge5 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4

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

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.

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

You can create custom mands under cypress/support/mands.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 mand as:

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

评论列表(0)

  1. 暂无评论