我试着在Cypress中做一个简单的测试,看看一个字段是否是只读的,但是不管我尝试了什么,我都无法让if语句工作,我已经检查了柏树文档,并且经历了大量不同类型的示例,我通常没有问题抓住元素并使用它们,但是我有点困惑,我错过了什么?
(我已经尝试过使用.hasClass和.find,但仍然没有成功,我也尝试使用元素的其他属性,但没有任何效果)
下面是我想要与之交互的字段的html代码:
<textarea _ngcontent-nud-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-pristine ng-valid cdk-text-field-autofill-monitored ng-touched"
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" style="height: 21px;"> </textarea>下面是我的代码来抓取它,并测试它是否包含文本“productName”:
cy.get('[formcontrolname="productName"]').then (($productName) => {
if ($productName.text().includes('productName')) {
cy.log('its found it');
} else {
cy.log('it hasnt found it');
}
});无论我尝试什么,if语句都会转到“它没有找到它”

发布于 2021-09-04 13:27:50
下面显示了对我有用的代码,以前我的If语句不能工作,在使用页面元素的别名时,我似乎无法选择我想要的文本字段,使用.val()函数解决了这个问题。使用.val(),我可以获取文本字段的值,然后将其与期望值进行比较,在我们的示例中,期望值是“粘土砖单元”
代码说明:我使用‘cy.get(’formcontrolname=“productName‘)’来获取我需要的文本字段,然后创建一个别名'$productName',然后使用.val()函数从文本字段($productName)返回值,然后使用if语句查看文本字段中的值是否包括‘粘土砖单元’,如果它确实输出了‘它找到它’,如果它没有找到输出‘它没有找到它’它没有找到它。
cy.get('[formcontrolname="productName"]').then(($productName) => {
const val = $productName.val() as string; // specify the returned value type
if (val.includes('Clay brick unit')) {
cy.log('its found it');
} else {
cy.log('it hasnt found it');
}
});
return this;
}发布于 2021-09-04 10:55:47
而不是text(),您必须使用.val()
cy.get('[formcontrolname="productName"]').then(($productName) => {
if ($productName.val().includes('Clay brick unit')) {
cy.log('its found it');
} else {
cy.log('it hasnt found it');
}
})发布于 2021-09-04 10:57:00
我认为您正在尝试确认元素,如果是的话,您将需要.attr()而不是.text()
cy.get('[formcontrolname="productName"]').then (($productName) => {
if ($productName.attr('formcontrolname').includes('productName')) {
cy.log('its found it');
} else {
cy.log('it hasnt found it');
}
});但是实际上,如果它是not ,那么.then()部件就不会运行--测试将在cy.get('[formcontrolname="productName"]')上失败,因为.get()命令有一个内置的断言。
使用$productName.val()遇到的问题是类型记录,抱怨它无法解决返回哪种类型。
试一试
const val = $productName.val() as string; // specify the returned value type
if (val.includes('Clay brick unit')) {https://stackoverflow.com/questions/69054273
复制相似问题