尝试从Cypress中的元素获取属性时出错

Bre*_*dan 13 cypress

我有这个HTML元素:

<input id="" type="text" name="last_name" value="Userc7bff2d0-7faf-11e8-9884-8fe4c5df7f77-Updated" class="medium" maxlength="2000" autocomplete="off" tabindex="" data-reactid=".0.2.0.1.0.2.1.0.1.0.0.1:0.1.0.1.2:$/=10">
Run Code Online (Sandbox Code Playgroud)

我想获得它的value属性来断言它已经通过我的测试进行了更新。

我尝试使用its()

cy
  .get(selector)
  .its("value")
  .should("contain", "-Updated");
Run Code Online (Sandbox Code Playgroud)

但是得到错误:

CypressError:超时重试:cy.its()错误,因为主题上的属性'value'不存在。

我也尝试过invoke

cy
  .get(selector)
  .invoke("value")
  .should("contain", "-Updated");
Run Code Online (Sandbox Code Playgroud)

但是得到一个类似的错误:

CypressError:超时重试:cy.invoke()错误,因为您的主题上不存在属性“ value”。

在这两种情况下,get()命令的Cypress控制台输出都会value成功显示具有其属性的元素:

产生:输入id =“” type =“ text” name =“名字” value =“伪更新” class =“ medium” maxlength =“ 2000” autocomplete =“ off” tabindex =“” data- reactid =“。0.2 .0.1.0.2.1.0.1.0.0.1:0.1.0.0.2:$ / = 10“

我有点为难。如果您需要更多信息或有什么想法请告诉我。

Saj*_*eri 12

你可以用这个

cy.get('a') // yields the element
  .should('have.attr', 'href') // yields the "href" attribute
  .and('equal', '/home') // checks the "href" value
Run Code Online (Sandbox Code Playgroud)

或者

cy.get('a').should('have.attr', 'href', '/home')
Run Code Online (Sandbox Code Playgroud)

有关更多详细信息,请检查: https://docs.cypress.io/api/commands/should#Method-and-Value


bku*_*era 9

invoke()在元素上调用jquery函数。要获取输入值,请使用以下函数val()

cy.get('input').invoke('val').should('contain', 'mytext')
Run Code Online (Sandbox Code Playgroud)

这是与获取的值属性,其将不与用户输入更新,它只有当元件呈现预设的值。要获取属性,可以使用jquery函数attr()

cy.get('input').invoke('attr', 'placeholder').should('contain', 'username')
Run Code Online (Sandbox Code Playgroud)


lak*_*ara 7

如果以上答案不起作用,请尝试这个,

cy.get('input[placeholder*="Name"]')
Run Code Online (Sandbox Code Playgroud)

查找占位符属性包含单词“Name”的输入。


Mat*_*bin 5

现在有一个插件可以满足您的需求。

https://github.com/Lakitna/cypress-commands/blob/develop/docs/attribute.md

有了这个,你将能够做到:

cy.get('input').attribute('placeholder').should('contain', 'username');
Run Code Online (Sandbox Code Playgroud)