有没有一种方法可以在 Cypress 的条件语句中使用 'exist'?

huangapple go评论58阅读模式
英文:

Is there a way to use 'exist' in a conditional statement in Cypress?

问题

我需要检查多个页面是否存在列表,并且如果存在,则获取列表的长度。这个方法是有效的,但是有些页面没有列表(这是有意的)。有没有办法我可以使用.should('exist')来检查列表是否存在,如果存在则进行检查,否则继续执行?

我目前有这个测试代码:

if (cy.get('.mt-5').should('exist')) {
    cy.get('.mt-5')
        .find('li')
        .then(($listItems) => {
            const listLength = $listItems.length;
            cy.wrap(listLength).as('listLength');
        });
}

然而,当到达if语句时,这会导致超时,因为它在查找.mt-5,但不是每个页面都有它。

英文:

I need to check multiple pages for whether a list exists, and if so, get the length of the list. This works fine except some pages do not have lists (this is intentional). Is there any way I can use .should('exist') to check if the list is there and if so check it, otherwise just continue?

I currently have this test:

if (cy.get('.mt-5').should('exist')) {
    cy.get('.mt-5')
        .find('li')
        .then(($listItems) => {
            const listLength = $listItems.length;
            cy.wrap(listLength).as('listLength');
        });
}

however, this just causes a timeout when it gets to the if statement as it is looking for .mt-5 which does not always exist.

答案1

得分: 3

The command cy.get('.mt-5') 无法用作if()语句中的测试条件,但您可以尝试使用Cypress.$('.mt-5')来代替。

问题在于您会失去cy.get()内置的重试功能。最好不要在测试中使用条件语句,而是尝试设置测试条件,以确保您始终具有该元素。

if (Cypress.$('.mt-5').length) {
    cy.get('.mt-5')
        .find('li')
        .then(($listItems) => {
            const listLength = $listItems.length;
            cy.wrap(listLength).as('listLength');
        });
}

如果您确实需要使用条件测试,并且需要等待.mt-5元素,可以通过元素轮询来添加自己的重试。请参考如何使用Cypress检查可能不存在的元素

英文:

The command cy.get('.mt-5') can't be used as a test in the if() statement, but you can try using Cypress.$('.mt-5') instead.

The problem will be that you loose the retry built in to cy.get(). It would be preferable not to use a conditional statement in the test, instead try to set up the test condition such that you always have that element.

if (Cypress.$('.mt-5').length) {
    cy.get('.mt-5')
        .find('li')
        .then(($listItems) => {
            const listLength = $listItems.length;
            cy.wrap(listLength).as('listLength');
        });
}

If you really have to use conditional testing, and need to wait for the .mt-5 element, there is a way to add your own retry via element polling.

See How to check for an element that may not exist using Cypress

huangapple
  • 本文由 发表于 2023年6月13日 00:35:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458641.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定