【问题标题】:Cypress: Unable to interact with page element赛普拉斯:无法与页面元素交互
【发布时间】:2021-09-08 11:19:51
【问题描述】:

我正在尝试确定某个字段是否为只读字段。当元素处于只读状态时,html代码如下所示:

<textarea _ngcontent-njf-c545="" rows="1" cdktextareaautosize="" aria-label="Product name" matinput="" type="text" placeholder="'Enter a product name...'" required="" formcontrolname="productName" class="cdk-textarea-autosize mat-input-element mat-form-field-autofill-control ng-tns-c98-55 ng-untouched ng-pristine cdk-text-field-autofill-monitored" ng-reflect-enabled="" ng-reflect-type="text" ng-reflect-placeholder="'Enter a product name...'" ng-reflect-required="" ng-reflect-name="productName" id="mat-input-3" data-placeholder="'Enter a product name...'" aria-invalid="false" aria-required="true" disabled="" style="height: 21px;">              </textarea>

有问题的字段是产品名称字段:

我们可以看到我们的元素有一个“禁用”属性,该属性仅在该字段被禁用时才存在,对于我的测试,我想确定我的元素中是否存在禁用属性,如果存在,那么我可以假设该元素将被禁用,如果没有,则该字段将被启用

如果我使用以下代码,我可以选择该字段并成功识别其是否为只读

cy.get('[formcontrolname="productName"]').should('be.disabled);

因此,尽管上面的代码可以工作,但该字段被禁用,但如果该字段未被禁用,代码将中断并抛出错误 因此,为了绕过我看到的示例,当我们执行这样的测试时,我们需要使用带有条件 If 语句的 .then() 函数 下面的代码选择页面上包含[formcontrolname="productName"]的元素,这是我们的产品名称字段,并将其传递到我们的If语句中以便我们可以使用它,然后脚本会尝试识别元素中是否存在“禁用”文本 它不起作用,虽然该字段已禁用,但我无法在元素中找到“禁用”文本

cy.get('[formcontrolname="productName"]').then((productName) => {
if (productName.find('disabled').length > 0) {
        cy.log('Field is disabled');
      } else {
        // do nothing
        cy.log('Field isn’t disabled');
      }
    });

因此,尽管此代码成功识别该字段是否为只读,但我无法使用它,因为如果该字段未禁用,测试将中断

  cy.get('[formcontrolname="productName"]').should('be.disabled);

但是一旦我使用 .then() 并出于某种原因将字段作为参数传递,我就无法以任何方式与元素交互 我已经尝试了很多其他方法

has.class 已禁用

.shoud(be.disabled) – 抛出错误

Has.attri,已禁用

任何帮助表示赞赏

【问题讨论】:

    标签: typescript cypress


    【解决方案1】:

    您可以为此使用:disabled jquery 方法:

    cy.get('[formcontrolname="productName"]').then(($ele) => {
      if ($ele.is(":disabled")) {
        cy.log("Field is disabled");
      } else {
        // do nothing
        cy.log("Field isn’t disabled");
      }
    });
    

    您也可以使用.attr()来检查元素是否包含以空字符串为值的禁用属性。

    cy.get('[formcontrolname="productName"]').then(($ele) => {
      if ($ele.attr("disabled") == "") {
        cy.log("Field is disabled");
      } else {
        // do nothing
        cy.log("Field isn’t disabled");
      }
    });
    

    【讨论】:

    • 感谢您的回复,我最终使用了您的第一个示例,效果很好:)
    猜你喜欢
    • 1970-01-01
    • 2020-12-23
    • 1970-01-01
    • 2018-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-28
    • 1970-01-01
    相关资源
    最近更新 更多