如何检查元素是否可见,然后单击该元素的按钮 CYPRESS

0 automated-tests cypress

目前我的网站在登录时经常在同一个div上返回固定的弹出窗口,但数量不固定。

我想检查div是否存在,然后单击关闭弹出窗口,如果不存在,则登录后继续执行下一步操作。

我尝试编写以下内容,但是当关闭所有弹出窗口时,程序继续检查 div 是否可见,然后抛出断言错误

    var checkAndClosePopup = () => {
  const dialogContainer = '//*[@role="dialog"]';
  const dialogContainerButton = '//*[@role="dialog"]//button[1]';

  var isPopupDisplay = () =>{
    return cy.xpath(dialogContainer).should('be.visible')
  }   

  cy.xpath(dialogContainerButton).then($button =>  {
    let isButtonVisible = $button.is(':visible');
    if(isPopupDisplay() && isButtonVisible){
      waitForSecond(1);
      cy.xpath(dialogContainerButton).click();
      checkAndClosePopup();
    }else 
      {
        return;
      }
  })
  }
Run Code Online (Sandbox Code Playgroud)

Tes*_*ick 5

要检查两个.if()条件,您可以链接.if()命令,但要小心出错,.else()因为没有正常if {...} else {...}语句中的括号。

const dialogContainer = '//*[@role="dialog"]';
const dialogContainerButton = '//*[@role="dialog"]//button[1]';

cy.xpath(dialogContainer)
  .if('visible')
  .xpath(dialogContainerButton)
  .if('visible')
  .click()
  .log('dialog button is visible')
  .else()
  .log('dialog button not visible')
  .else()
  .log('dialog not visible')
Run Code Online (Sandbox Code Playgroud)

最好添加一个.then()来包装第二个条件

const dialogContainer = '//*[@role="dialog"]';
const dialogContainerButton = '//*[@role="dialog"]//button[1]';

cy.xpath(dialogContainer)
  .if('visible')
  .then(() => {
    cy.xpath(dialogContainerButton)
    .if('visible')
    .click()
    .log('dialog button is visible')
    .else()
    .log('dialog button not visible')
  })
  .else()
  .log('dialog not visible')
Run Code Online (Sandbox Code Playgroud)

循环消除多个弹出窗口

不确定这是否有效,但请尝试。

在容器上添加 10 秒的超时来处理之间的延迟。

const dialogContainer = '//*[@role="dialog"]';
const dialogContainerButton = '//*[@role="dialog"]//button[1]';

function dismissOnePopup() {
  cy.xpath(dialogContainer, {timeout:10_000})  //timeout = max delay between
  .if('visible')
  .then(() => {
    cy.xpath(dialogContainerButton)
    .if('visible')
    .click()
    .log('dialog button is visible')
    .else()
    .log('dialog button not visible')
  })
  .else()
  .log('dialog not visible')
}

Cypress._.times(10, () => {
  dismissOnePopup()
})
Run Code Online (Sandbox Code Playgroud)

查找最多 10 个弹出窗口,每个弹出窗口之间最多间隔 10 秒。

如果实际发生的情况较少,则该.else()部分将因缺席而运行。

问题是,如果没有发生任何情况,您将等待整整 10 秒。

阻止循环自身溢出

在测试内部cy.each()将等待内部命令完成,然后再进行下一次迭代。

const dialogContainer = '//*[@role="dialog"]';
const dialogContainerButton = '//*[@role="dialog"]//button[1]';

cy.wrap([...Array(10)].each(() => {

  cy.xpath(dialogContainer, {timeout:10_000})  //timeout = max delay between
  .if('visible')
  .then(() => {
    cy.xpath(dialogContainerButton)
    .if('visible')
    .click()
    .log('dialog button is visible')
    .else()
    .log('dialog button not visible')
  })
  .else()
  .log('dialog not visible')
})
Run Code Online (Sandbox Code Playgroud)