Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cypress "have.attr" with regular expressions

Tags:

cypress

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/));
like image 480
Daniel Avatar asked Aug 31 '19 07:08

Daniel


People also ask

How do I get attr value in Cypress?

Using data attribute To find elements by data attribute, query using the attribute selector. cy. get() yields a jQuery object, you can get its attribute by invoking the . attr() method.

How do I use attr in Cypress?

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.


1 Answers

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/);
like image 148
jonrsharpe Avatar answered Sep 30 '22 07:09

jonrsharpe