赛普拉斯:测试元素是否存在

时间:2020-02-26 21:03:39

标签: if-statement testing automated-tests cypress

我是赛普拉斯的新手,我知道之前曾有人问过这个问题,但我仍然被困在这里! 这是我写的:

 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循环中……任何想法关于如何解决这个问题?谢谢!

所以我再次更新了代码,因为正如理查德·马特森(Richard Matsen)正确指出的那样,此条件($body.find($el.length>0))总是评估为true。现在发生的事情是它计算长度为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();
      }
   })
 })

1 个答案:

答案 0 :(得分: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 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();
        }
    })
})

我所做的一些更改是:

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