如何使用赛普拉斯检查可能不存在的元素 [英] How to check for an element that may not exist using Cypress

查看:377
本文介绍了如何使用赛普拉斯检查可能不存在的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在编写赛普拉斯测试以登录网站.有用户名和密码字段以及一个提交按钮.通常情况下,登录很简单,但有时会先显示警告对话框,而必须将其关闭.

I am writing a Cypress test to log into a website. There are username and password fields and a Submit button. Mostly logins are straightforward, but sometimes a warning dialog appears first that has to be dismissed.

我尝试过:

    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();
    }

正常运行,除了如果未出现警告则测试失败:

which works fine, except that the test fails if the warning doesn't appear:

CypressError: Timed out retrying: Expected to find element: '.warning', but never found it.

然后我尝试了此操作,但由于警告显示的速度不够快而失败,因此Cypress.$找不到任何东西:

Then I tried this, which fails because the warning doesn't appear fast enough, so Cypress.$ doesn't find anything:

    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的东西,如果找不到该元素,它也不会抱怨.

What is the correct way to check for the existence of an element? I need something like cy.get that doesn't complain if the element can't be found.

推荐答案

尝试对DOM元素进行条件测试有很多弊端,赛普拉斯也有各种解决方法.赛普拉斯文档中的条件测试中对此进行了详细说明.

There are various downsides to attempting to do conditional testing on DOM elements and also various workarounds in Cypress. All of this is explained in depth in the Cypress documentation in Conditional Testing.

由于有多种方法可以完成您想做的事情,因此建议您通读整个文档,并确定最适合您的应用程序和测试需求的方法.

Since there are multiple ways to do what you are trying to do, I suggest you read through the entire document and decide what is best for your application and your testing needs.

这篇关于如何使用赛普拉斯检查可能不存在的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆