DEV Community

Alessio Michelini
Alessio Michelini

Posted on • Updated on

[Code snippets] Testing html anchor links in Cypress

Check the link is a valid page

One way is to check that if I click on a link, it goes to a valid page.

it('should follow the CTA button', () => {
  cy.get('.my-fancy-link')
    .then((link) => {
      cy.request('HEAD', link.prop('href'))
        .its('status')
        .should('eq', 200);
    });
});
Enter fullscreen mode Exit fullscreen mode

The above code essentially emulates what your browser does, it takes the href value of the link, does a request using the HEAD method (to avoid to get the full response) to that page, and if the status is a 200 OK, it simply means that the destination page is correct.

Follows the link and check the url

Another way is to tell Cypress to actually click the link, and check the current url of the page.

it('should follow the CTA button', () => {
  cy.get('.contact-sales')
    .click()
    .then(() => {
      cy.url().should('eq', 'https://example.com');
      cy.visit('/page/you/are/testing');
    });
});
Enter fullscreen mode Exit fullscreen mode

The only problem of the latter method, is that you have to tell to cypress to go back to the previous page.

Bonus

In some cases the domain you are testing might have queryparams that are difficult to predict, in that case you can test if the url matches what are you testing using a different strategy than cy.url(), and use cy.location() instead:

it('should follow the CTA button', () => {
  cy.get('.contact-sales')
    .click()
    .then(() => {
      cy.location().should((location) => {
         expect(location.origin).to.eq('https://example.com.com');
      });
      cy.visit('/page/you/are/testing');
    });
});
Enter fullscreen mode Exit fullscreen mode

Oldest comments (0)