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

Top comments (0)

The JavaScript Brief

1. Top 5 MERN STACK projects to improve your practical understanding

Boost your MERN Stack development skills by undertaking interesting beginner projects. These five engaging projects cover web applications and range from social media website applications to geo-social networking maps. Hone your understanding and apply modern techniques backed up by hands-on experience.

2. How To Optimize Your React App’s Performance

Learn the best optimizing techniques to make your React applications faster and more efficient. Focusing on the identification of performance bottlenecks and common pitfalls to avoid, these optimization strategies will keep your applications running smoothly even when faced with growing complexity.

3. A story of let, const, object mutation, and a bug in my code

In the pursuit of bug-free code, explore an incident involving a mix-up between const and let, making sure your custom code works effectively with third

party documentation. Discover best practices on program flow and learn about JavaScript's unpredictable aspects to ensure your core code is robust.