I have a fairly complex test involving quite a few elements on the page, need to save the values and use them later in an assertion.
Currently I am using aliases to save the values, as per the docs recommendation. Is there a way to avoid deeply nesting like this?
For example,
cy.get(selector1).invoke('val').as('alias1')
cy.get(selector2).invoke('val').as('alias2')
cy.get(selector3).invoke('text').as('alias3')
cy.get(selector4).invoke('text').as('alias4')
cy.get(selector5).invoke('text').as('alias5')
// etc
cy.get('@alias1').then((val1) => {
cy.get('@alias1').then((val2) => {
cy.get('@alias1').then((val3) => {
cy.get('@alias1').then((val4) => {
cy.get('@alias1').then((val5)=> {
// assert values against fixture
expect([val1, val2, val3, val4, val5]).to.deep.eq(myFixture)
>Solution :
When you set an alias, it is also added as a property of the test context object.
You can use the function syntax to access "this" context, and read the values in a single callback at the end of the test.
cy.get(selector1).invoke('val').as('alias1')
cy.get(selector2).invoke('val').as('alias2')
cy.get(selector3).invoke('text').as('alias3')
cy.get(selector4).invoke('text').as('alias4')
cy.get(selector5).invoke('text').as('alias5')
cy.then(function() {
const actual = [this.val1, this.val2, this.val3, this.val4, this.val5]
expect(actual).to.deep.eq(myFixture)
})