如何检查元素是否存在,然后才 运行 使用 Cypress 进行测试?

How to check if an element exists and only then run a test with Cypress?

我只想在特定元素存在时使用其数据测试 ID 执行某些功能。

以下是我正在尝试做的事情:

cy.getByTestId('checkbox-id').then((el) => {
    if (el) {
        cy.tableSelectAll();
    }
}

这里我希望它只在有元素时才执行 tableSelectAll()。但这并没有说明它找不到 ID 为“checkbox-id”的元素。

我该如何解决这个问题?有人可以帮我解决这个问题吗?

您可以使用 jquery 方法 .attr 检查属性 data-testid 是否存在。

cy.get('checkbox-id').then(($ele) => {
  if ($ele.attr('data-testid')) {
    cy.tableSelectAll()
  } else {
    //Do something else
  }
})

您想遵循这种模式Element existence

cy.get('body')
  .then(($body) => {
    // synchronously query from body
    // to find which element was created
    if ($body.find('[data-testid="checkbox-id"]').length) {
      // checkbox-id was found
      cy.tableSelectAll()
    }
  })