Search code examples
foreachcypressboolean-expression

How to solve setting a value to true inside a foreach loop while also setting the value to true on the outside of the loop in Cypress


I am having some issues trying to solve this problem. What I'd like to happen is if the forEach loop does NOT find the first text after running through all the cells. Then the final if block on the outside should run, and assert that the first text cell was not found.

Thank you :-)

Cypress.Commands.add("aCommand", (Locator, firstCellText, secondCellText) => {

  let firstCellTextFound = false
  cy.get("aDifferentLocator").find(Locator).each($cell => {
    let text = $cell.text()

    if (text.includes(firstCellText)) {
      cy.wrap($cell).next().should("have.text", secondCellText)

      firstCellTextFound = true
    }
  })

  if(firstCellTextFound == false)
  {
    expect(firstCellTextFound).to.be.true
  }
})

Solution

  • Your outside if block is synchronous code, while your cy.get() command is asynchronous, so the if block will execute while the cy.get().each() is still running. Wrapping that final if in a .then() block should solve your problem.

    let firstCellTextFound = false
    cy.get("aDifferentLocator").find(Locator).each($cell => {
      ... code ...
    }).then(() => {
      if(firstCellTextFound == false) {
        expect(firstCellTextFound).to.be.true
      }
    })