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/));
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.
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.
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/);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With