Cypress - 如何在 Cypress 中进行轮询?

Pra*_*tel 2 ui-automation long-polling cypress

在网络应用程序上,特定元素仅在页面重新加载后才可见,并且在一段时间后也可用,因此目前我已将其实现如下:

it('element-check', () => {
    cy.visit('url')
// performing certain actions 
    cy.wait(150000)
    cy.reload()
    cy.contains('text').click()
})
Run Code Online (Sandbox Code Playgroud)

我需要使用轮询机制,而不是固定等待 cy.wait(150000),每隔 30 秒重新加载页面并检查所需的元素,直到该元素可见。

Ala*_*Das 6

您可以使用递归函数来实现此目的。

it('element-check', () => {
  cy.visit('url')

  let retry = 0
  function isElementVisible() {
    
    if (retry < 5 && Cypress.$('selector').length == 0) {

      //Increment retry
      retry++

      //wait 30 seconds
      cy.wait(30000)

      //Reload Page
      cy.reload()

      //Element is not yet visible, Call the recursive function again
      cy.then(isElementVisible)

    } else if (retry < 5 && Cypress.$('selector').length == 1) {
      cy.get('selector').click()
      return

    } else {
      //It excedded required no. of execution
      return
    }
  }
  //Trigger the recursive function
  cy.then(isElementVisible)
})
Run Code Online (Sandbox Code Playgroud)

  • 无界递归是不好的做法。 (4认同)