1

I want to check if a text/comment at a special location is like expected. If so, I want to count up itemFound by 1. The problem is, that I can't bring the variable to the outer scope. (later I want to search many locations for this element)

let itemFound = 0;
cy.xpath('//table/div/span').then((item) => {
    let comment = item.text().trim();
    if (comment == "myuniquecomment")
    {
        itemFound += 1;
    }
    cy.log(itemFound)     // okay 
})

cy.log(itemFound)  // not okay
kame
  • 20,848
  • 33
  • 104
  • 159
  • 1
    The problem isn't scope, it's *timing*. You're looking at the value of the variable before the promise settles. You should look at it *after* – T.J. Crowder Apr 25 '22 at 14:07
  • 1
    Take a look at [Visualize cypress command queue](https://glebbahmutov.com/blog/visualize-cypress-command-queue/) to see the order of execution for your code. – Fody Apr 25 '22 at 22:41
  • 1
    Essentially `cy.then(() => cy.log(itemFound))` will work because it's enqueuing the log command after previous commands have run. – Fody Apr 25 '22 at 22:44
  • To think of Cypress code as promises is incorrect, it's better to understand that the command queue runs ***after*** the test block has run. – Fody Apr 25 '22 at 22:50
  • 1
    @Fody Your second comment is the solution! – kame Apr 26 '22 at 06:16
  • @Fody So the duplicate link is wrong? How to inform T.J. Crowder? @t-j-crowder? – kame Apr 26 '22 at 06:46
  • 1
    The duplicate link is frankly monstrous, I don't know how you are supposed to apply it. The broad principle is the same, but the resolution is different. This Cypress question has been asked a lot of times before, but tracking them down is quite difficult even when I answered them myself. I just thought you deserved a better response. – Fody Apr 26 '22 at 07:09

0 Answers0