skies.dev

How to Find Dead Links with Cypress Testing Library

2 min read

You know that feeling when you're on a website, you click a link, and you see 404?

It's frustrating, but understandable as content creators often don't have the bandwidth to ensure external (or even internal) links haven't broken over time.

Luckily for us, Cypress Testing Library makes it easy to ensure the links on our site work without manual, human intervention.

The process is simple:

  1. Process each link on the page by targeting the anchor (<a>) elements.
  2. Do an HTTP request against the link's URL to ensure the link still works.

If the HTTP response status code is greater than or equal to 400, the test will fail. If the test fails, you'll know if you need to update the link.

// 1. Process each link on the page by targeting the anchor (`<a>`) elements.
cy.get('a').each((link) => {
  // 2. Do an HTTP request against the link's URL to ensure the link still works.
  cy.request(link.prop('href'));
});

Keep in mind issuing an HTTP request for each link is going to slow down You may want to limit the surface area of links you check using cy.within. For example:

cy.get('#main-content').within(() => {
  cy.get('a').each((link) => {
    cy.request(link.prop('href'));
  });
});

With this, you can feel at ease knowing the links your users are clicking will work.

Hey, you! 🫵

Did you know I created a YouTube channel? I'll be putting out a lot of new content on web development and software engineering so make sure to subscribe.

(clap if you liked the article)

You might also like