我正在编写 Cypress 测试来登录网站。有username
and password
字段和一个Submit
按钮。大多数登录都很简单,但有时首先会出现一个警告对话框,必须将其关闭。
我试过这个:
cy.get('#login-username').type('username');
cy.get('#login-password').type(`password{enter}`);
// Check for a possible warning dialog and dismiss it
if (cy.get('.warning')) {
cy.get('#warn-dialog-submit').click();
}
哪个工作正常,除了如果不出现警告则测试失败:
CypressError:重试超时:期望找到元素:“.warning”,但从未找到它。
然后我尝试了这个,但失败了,因为警告出现的速度不够快,所以Cypress.$
没有找到任何东西:
cy.get('#login-username').type('username');
cy.get('#login-password').type(`password{enter}`);
// Check for a possible warning dialog and dismiss it
if (Cypress.$('.warning').length > 0) {
cy.get('#warn-dialog-submit').click();
}
检查元素是否存在的正确方法是什么?我需要类似的东西cy.get()
如果找不到该元素,则不会抱怨。
Use 元素轮询并检查是否未通过测试。
在最大等待时间内,要么对话框永远不会到达,要么此代码将其关闭。
cy.get('#login-username').type('username');
cy.get('#login-password').type(`password{enter}`);
const ifElementExists = (selector, attempt = 0) => {
if (attempt === 100) return null // no appearance, return null
if (Cypress.$(selector).length === 0) {
cy.wait(100, {log:false}) // wait in small chunks
getDialog(selector, ++attempt) // try again
}
return cy.get(selector, {log:false}) // done, exit with the element
}
ifElementExists('.warning').then($el => {
if ($el?.length) {
$el.find('#warn-dialog-submit').click()
}
})
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)