What is the best practice of pass states between tests in Cypress

早过忘川 提交于 2020-12-30 07:51:07

问题


I want to pass/share data between each test. What is the best way to implement it in Cypress?

For example:

 it('test 1'), () => {
   cy.wrap('one').as('a')
   const state1 = 'stat1'
 })

 it('test 2'), () => {
   cy.wrap('two').as('b')
 })

 it('test 2'), () => {
   //I want to access this.a and this.b

   //Also I want to access state1

 })

回答1:


In the case of Javascript variables, you can do something like this:

let state;

describe('test 1', () => {
    it('changes state', () => {
        state = "hi";
     });
});

describe('test 2', () => {
    it('reports state', () => {
        cy.log(state); // logs "hi" to the Cypress log panel
     });
});

.as() does not appear to be able to carry state between describe blocks.




回答2:


Assuming you are trying to pass text

it('test 1'), () => {
  cy.wrap('one').as('a')
}

it('test 2'), () => {
  cy.wrap({ valueName: 'two' }).as('b')
}

it('test 2'), () => {
  //I want to access this.a and this.b
  cy.get('@a').then((thisIsA) => {
    cy.log(thisIsA);
    // logs 'one'
  }

  cy.get('@b').its('valueName').then((thisIsB) => {
    cy.log(thisIsB);
    // logs 'two'
  }

  cy.get('@b').its('valueName').should('eq', 'two')
}



回答3:


I tried some of these other solutions and they aren't working for me. Maybe things changed with recent versions. The following example should work. Note the use of function() for both tests which keeps things in context of 'this.'.

  it('get the value', function () {
    cy.get('#MyElement').invoke('text').as('mytext1')
  })

  it('use the value', function () {
    cy.log(this.mytext1);
  })


来源:https://stackoverflow.com/questions/52050657/what-is-the-best-practice-of-pass-states-between-tests-in-cypress

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!