Cypress “have.attr” with regular expressions

寵の児 提交于 2021-02-07 12:32:18

问题


In Cypress I can match an attribute's value by exact text like this:

cy.get("my-element")
  .should("have.attr", "title", "Exact title")

But, is there a way to match the attribute's value by a substring or a regular expression? something like:

cy.get("my-element")
  .should("have.attr", "title", /Partial title/)

So far, this is the best I have:

cy.get("my-element")
  .should("have.attr", "title")
  .then(title => expect(title).to.match(/Partial title/));

回答1:


Per the Cypress docs, have.attr comes from chai-jquery:

attr(name[, value])

Assert that the first element of the selection has the given attribute, using .attr(). Optionally, assert a particular value as well. The return value is available for chaining.

$('#header').should.have.attr('foo');
expect($('body')).to.have.attr('foo', 'bar');
expect($('body')).to.have.attr('foo').match(/bar/);

It only takes an exact value for the attribute directly. However, because the return value changes the subject, you can use chaining as also shown in the Cypress docs:

cy
  .get('nav')                          // yields <nav>
  .should('be.visible')                // yields <nav>
  .should('have.css', 'font-family')   // yields 'sans-serif'
  .and('match', /serif/)

In your case that would be

cy.get("my-element")
  .should("have.attr", "title")
  .and("match", /Partial title/);


来源:https://stackoverflow.com/questions/57736076/cypress-have-attr-with-regular-expressions

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!