Checking length of element in beforeEach on Cypress

Solution 1:

Cypress commands are asynchronous. So when the test executes cy.visit("/") it does not mean that the next line will be executed after the page gets really loaded.

You can fix this as follows:

 beforeEach(() => {
    cy.visit("/").then(() => {
      let count = Cypress.$('#emails').length
      cy.log(count)
      if(count == 0) {
        createNewEmail()
      }
    })
}