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循环中。。。关于如何解决这个问题有什么想法吗?谢谢

所以我再次更新了我的代码,因为这个条件($body.find($el.length>0))总是计算为true,正如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();
}
})
})

使用这个:怎么样

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基于该结果

最新更新