小编pon*_*ous的帖子

Cypress:如果元素存在则做某事

我遇到的问题是如果元素存在则执行某些操作。举个例子:

if (cypress.$('.row > .text-right > .btn').length > 0) {
            cy.get('.row > .text-right > .btn').click();
          }
Run Code Online (Sandbox Code Playgroud)

这里的问题是,如果按钮不存在,cypress 就会中止测试,但这正是 cypress 不应该中止的时候,它应该不执行任何操作并继续。

我需要一个解决方案

if (element.exists) {
   cy.get(element).click();
    }
Run Code Online (Sandbox Code Playgroud)

javascript cypress

9
推荐指数
1
解决办法
8621
查看次数

为什么我的别名会更改为不同的元素?

我有以下代码:

cy.get('input:checkbox').first().as('firstCheckbox').then(() => {

    cy.get('@firstCheckbox').should('be.checked').click()
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('be.visible')
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('not.exist')
    cy.get('@firstCheckbox').should('not.be.checked').click()
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('be.visible')
    cy.get('.globalMessage-display > :nth-child(1) > .alert').should('not.exist')
    cy.get('@firstCheckbox').should('be.checked')

})
Run Code Online (Sandbox Code Playgroud)

cy.get('@firstCheckbox').should('be.checked').click()将复选框移动到最后一个索引位置而不是第一个索引位置后。根据我对别名的理解,这应该不重要,因为我引用它并且('@')它在哪个位置并不重要。不幸的是,下一个cy.get('@firstCheckbox')访问新的第一个元素,而不是我最初引用的元素。我也无法从文档中弄清楚。错误在哪里?

https://docs.cypress.io/guides/core-concepts/variables-and-aliases

https://docs.cypress.io/api/commands/as

@agoff 的更新:

它似乎更适合您的代码,但我注意到新代码存在一个新问题。如果您取消选中该复选框,则该类将使用 js 重新加载,导致它短暂地从 dom 中消失。之后它就找不到它了,测试中止。我也尝试过重新加载,但它再也找不到该元素了。这该如何处理呢?

选中的复选框类的名称为custom-control-input ng-untouched ng-pristine ng-valid。取消选中类名后更改为custom-control-input.ng-untouched.ng-valid.ng-dirty一秒钟,然后元素被删除并使用类名重新加载到 DOM 中custom-control-input ng-untouched ng-pristine ng-valid。问题在于,尽管搜索并找到了具有该类的初始cy.wrap($el)元素,但第二个元素仍尝试查找该元素。这是我不明白的另一件事。custom-control-input.ng-untouched.ng-valid.ng-dirtycustom-control-input ng-untouched ng-pristine ng-valid

javascript jquery cypress

3
推荐指数
1
解决办法
2350
查看次数

标签 统计

cypress ×2

javascript ×2

jquery ×1