Neil Dello
Neil Dello

Reputation: 53

Testing attribute text to match part of href link in Cypress

I'm testing all the links on a page but I only want a partial match.

I can test the full href like this

cy.visit('/');
cy.get('.class').find('a').should("have.attr", "href", "/123/456");

but I want to test the string partially, for example /456. I tried .contains() but it doesn't work.

Upvotes: 5

Views: 2265

Answers (1)

Fody
Fody

Reputation: 31944

You could use include,

cy.get('.class').find('a')
  .should('have.attr', 'href')
  .and('include', '/456');

or you can switch the subject

cy.get('.class').find('a')
  .invoke('attr', 'href')
  .should('contain', '/456');

or a longer version using jquery

cy.get('.class').find('a')
  .should('have.attr', 'href')
  .then(href => {
    expect(href.endsWith('/456')).to.be.true;
  });

Upvotes: 5

Related Questions