cypress - do action until element shows on screen

橙三吉。 提交于 2020-02-29 06:46:08

问题


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 testing a KaiOS app that instead of scrolling, uses page flipping similar to a kindle device to make it easier for the user to read.

Currently, since KaiOS is based on Firefox OS, the only way to use the app on a computer in a similar way to the device is to use firefox. The problem is that the page flipping when running the tests on cypress (even with firefox) is not working as expected so when we flip the page it doesn't go to the same page as it does on the device or firefox.

So, since I can't make sure how to find the element I'm looking for, I need to keep flipping pages and look for it and then interact with it.

I have tried a bunch of different things without success.

What I need is fairly simple:

  1. go to page
  2. check for presence of element, if not present, flip page. keep flipping pages until it finds the element
  3. once it found the element, interact with it

回答1:


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 😊




回答2:


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



来源:https://stackoverflow.com/questions/60431148/cypress-do-action-until-element-shows-on-screen

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!