Cha*_*son 12 automated-tests cypress
我正在写一个赛普拉斯测试来登录一个网站.有用户名和密码字段以及提交按钮.大多数登录都很简单,但有时会出现一个必须被解除的警告对话框.
我试过这个:
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();
}
Run Code Online (Sandbox Code Playgroud)
哪个工作正常,但如果没有出现警告则测试失败:
CypressError: Timed out retrying: Expected to find element: '.warning', but never found it.
Run Code Online (Sandbox Code Playgroud)
然后我尝试了这个,因为警告不够快,所以赛普拉斯.$没有找到任何东西:
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();
}
Run Code Online (Sandbox Code Playgroud)
检查元素是否存在的正确方法是什么?我需要像cy.get这样的东西,如果找不到元素就不会抱怨.
Fod*_*ody 45
使用元素轮询并进行检查,以免测试失败。
在最大等待时间内,要么对话框永远不会到达,要么此代码将其关闭。
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
ifElementExists(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()
}
})
Run Code Online (Sandbox Code Playgroud)
Ran*_*ler 14
export function clickIfExist(element) {
cy.get('body').then((body) => {
if (body.find(element).length > 0) {
cy.get(element).click();
}
});
}
Run Code Online (Sandbox Code Playgroud)
尝试对 DOM 元素进行条件测试有很多缺点,在 Cypress 中也有各种变通方法。所有这些都在 Cypress 文档中的Conditional Testing中进行了深入解释。
由于有多种方法可以完成您正在尝试执行的操作,因此我建议您通读整个文档并确定最适合您的应用程序和测试需求的方法。
| 归档时间: |
|
| 查看次数: |
15837 次 |
| 最近记录: |