cypress - do action until element shows on screen

前端 未结 2 448
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-16 03:01

I know that Cypress is not big on conditional testing, but coming from a selenium webdriver background, I\'m very used to using this kind of logic in my tests.

I am

相关标签:
2条回答
  • 2021-01-16 03:36

    I've already replied in the issues you raised but I'll write the solution here too to help other users.

    Well, step by step, you need to

    • go to page

    A simple

    cy.visit('<your url>')
    
    • check for presence of element

    The simplest way is to leverage the exposed Cypress.$ jQuery instance and checking by yourself if the element exists.

    cy.visit('<your url>')
    cy.waitUntil(() => !!Cypress.$('#elementToBeChecked').length)
    

    () => !!Cypress.$('#elementToBeChecked').length is the checkFunction expected by waitUntil, it returns a boolean and waitUntil retries it until it returns true.

    • check for presence of element, if not present, flip page
    cy.visit('<your url>')
    cy.waitUntil(() => {
      if (!Cypress.$('#elementToBeChecked').length) {
        return cy.flipPage().then(() => false)
      } else {
        return true
      }
    })
    

    the cy.flipPage().then(() => false is useful to be sure that che checkFunctin resolves to false. waitUntil will call the checkFunction until it returns true.

    • keep flipping pages until it finds the element

    Done

    • once it found the element, interact with it
    cy.visit('<your url>')
    cy.waitUntil(() => {
      if (!Cypress.$('#elementToBeChecked').length) {
        return cy.flipPage().then(() => false)
      } else {
        return true
      }
    })
    cy.get('#elementToBeChecked').click()
    

    If you want an even more detailed explanation about why you need waitUntil for a task like yours, take a look here.

    Hope it helps

    0 讨论(0)
  • 2021-01-16 03:45

    Try using https://github.com/NoriSte/cypress-wait-until to perform actions on the page conditionally

    0 讨论(0)
提交回复
热议问题