if-statement - 赛普拉斯:测试元素是否存在
问题描述
我是柏树的新手,我知道以前有人问过这个问题,但我仍然被困在这里!这是我写的:
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();
}
})
})
解决方案
如何使用这个:
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 基于该结果
推荐阅读
- python - 在 Django 中按类别添加产品而不使用 form.py
- javascript - Sequelize - 更新查询并返回:true 成功但返回 undefined
- php - 是否可以只允许使用一个 API 密钥访问 Laravel API?
- xml - 如何将xml中的requiredValue设置为任何值
- angular - 角度将图像传递给组件
- python - 在 python 中解析其 img 链接的 URL
- mysql - 如何计算日期错误之间的时间?
- c# - 如何访问主类之外的 WPF 控件属性
- javascript - $ 不是 wordpress 5.3 更新后的功能
- android - SQLITE:显示三个表差异与两个条件之间的差异