Comparing results of function call before and after page actions

Viewed 48

I have a complicated selection that I've put into a function to keep the test clean. I want to call the function before and after some page actions and compare the results.

This is my code, problem is I'm not getting the result back even though the value is extracted successfully inside the function.

const getVals = () => {
  // simplified
  cy.get('[id="22"] span')
    .then($els => {
      const vals = [...$els].map(el => el.innerText)
      return vals
    })
}

const vals1 = getVals()

// perform action on the page

const vals2 = getVals()

// compare
expect(vals1).to.deep.eq(vals2)
1 Answers

The function has a return inside .then() but it's not returning the result from the main body of the function.

Since the commands are asynchronous, I recommend changing to a custom command and adding alias to preserve the result during the intermediate actions

Cypress.Commands.add('getVals', () => {
  cy.get('[id="22"] span')
    .then($els => {
      const vals = [...$els].map(el => el.innerText)
      return vals                    // vals is Cypress "subject" 
    })
}

cy.getVals().as('vals1')

// perform action on the page

cy.getVals().then(vals2 => {         // use then to obtain vals
  cy.get('@vals1').then(vals1 => {   // retrieve first from alias
    // compare
    expect(vals1).to.deep.eq(vals2)
  })
})
Related