DWilches
DWilches

Reputation: 23035

Cypress "have.attr" with regular expressions

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/));

Upvotes: 24

Views: 30782

Answers (1)

jonrsharpe
jonrsharpe

Reputation: 122137

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/);

Upvotes: 49

Related Questions