问题
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