首页 > 解决方案 > 赛普拉斯:测试元素是否存在

问题描述

我是柏树的新手,我知道以前有人问过这个问题,但我仍然被困在这里!这是我写的:

 it("User can set certification for multiple users at once",()=>{
       cy.get(':nth-child(4) > .RadioButton__StyledRadioButton-sc-1j2qp2u-1').click(); //clicking Non-certified button
       const $el=Cypress.$('[class="Typography__StyledTypography-sc-153d8g4-0.jhYDmS.TrainingQueueListstyles__EmptyListMessage-sc-19yfim3-1.ihRiqU"]');
       cy.get("body").then($body =>{
        if ($body.find($el.length>0)) {
         cy.log('in if loop');
         cy.log($el.length);
         cy.get('.hZDZBR').should('not.exist');
         cy.get('input[id="selectAll"]').should('not.exist');
        } else {
        cy.log('in else loop');
        cy.log($el.length);
        cy.get('input[id="selectAll"]').click();
        cy.get('.hZDZBR').click();
      }
     })
    })

但是当$el找不到元素时(并且它记录$el.length=0了正确的),它仍然尝试执行 if 循环,而它应该在 else 循环中......关于如何解决这个问题的任何想法?谢谢!

所以我再次更新了我的代码,因为($body.find($el.length>0))正如 Richard Matsen 正确指出的那样,这个条件总是评估为真。现在发生的事情是它计算长度为0,因此进入else循环,但我可以在网页上看到该元素,但它的长度仍然为0..这是什么原因,我该怎么办?

it("User can set certification for multiple users at once",()=>{
       cy.get(':nth-child(4) > .RadioButton__StyledRadioButton-sc-1j2qp2u-1').click(); //clicking Non-certified button
       const $el=Cypress.$('[class="Typography__StyledTypography-sc-153d8g4-0.jhYDmS.TrainingQueueListstyles__EmptyListMessage-sc-19yfim3-1.ihRiqU"]');
       cy.get("body").then($body =>{
        if ($body.find($el).length>0) {
         cy.log('in if loop');
         cy.log($body.find($el).length);
         cy.get('.hZDZBR').should('not.exist');
         cy.get('input[id="selectAll"]').should('not.exist');
        } else if($body.find($el).length==0){
        cy.log('in else loop');
        cy.log($body.find($el).length);
        cy.get('input[id="selectAll"]').click();
        cy.get('.hZDZBR').click();
      }
   })
 })

标签: if-statementtestingautomated-testscypress

解决方案


如何使用这个:

it("User can set certification for multiple users at once",()=>{
    cy.get(':nth-child(4) > .RadioButton__StyledRadioButton-sc-1j2qp2u-1').click(); //clicking Non-certified button
    const selector=".Typography__StyledTypography-sc-153d8g4-0.jhYDmS.TrainingQueueListstyles__EmptyListMessage-sc-19yfim3-1.ihRiqU";
    cy.get("body").then($body =>{
        const $el = $body.find(selector);
        if ($el) {
            cy.log('in if loop');
            cy.get('.hZDZBR').should('not.exist');
            cy.get('input[id="selectAll"]').should('not.exist');
        } else {
            cy.log('in else loop');
            cy.get('input[id="selectAll"]').click();
            cy.get('.hZDZBR').click();
        }
    })
})

我所做的一些更改是:

  • 使用选择器而不是查询初始元素
  • 查询回调中的实际元素
  • If/Else 基于该结果

推荐阅读