Search code examples
cypresshref

Cypress to get only href in a page that contains specific path inside


I am trying to make a test that actually look into all the href in a page, and ONLY if the path url contains /example (mywebsite.com/example/anotherPage) inside the href, I want to test the url.

describe('VerifyProductsLinks', () => {
  it('passes', () => {
    cy.visit('/')
    cy.get('a').each((page) => {
      if (page.prop('href').should('contains', '/example')) {
        cy.request(page.prop('href'))
      }
    })
  })
})

This is what I tried, but I get the error page.prop is not a function. What I am doing wrong?


Solution

  • You can use Cypress to collect all a elements (assuming those are the ones with hrefs), iterate through them with cy.each(), and then only take actions if the element's href contains a certain value (by using the yielded element, JQuery's .prop() function, and JavaScript String .includes().

    cy.get('a').each(($a) => {
      if ($a.prop('href').includes('/example') {
        // cypress code here
        cy.request($a.prop('href'));
      }
    });
    

    Attempting to do an if/else on a Cypress command directly will not work as expected, as these commands do not yield a boolean value to be evaluated.