skies.dev

How to Find Dead Links with Cypress Testing Library

1 min read

Broken links are one of the easiest regressions to ship. They look harmless in review and then quietly send users to 404 pages later.

Content changes, external sites move, and old docs disappear. If you do not check links automatically, they will break eventually.

You can catch most of them with Cypress.

The basic flow is:

  1. Target each anchor (<a>) element on the page.
  2. Request the URL behind the link.
  3. Fail the test if the response status is 400 or higher.
// Check each anchor on the page.
cy.get('a').each((link) => {
  // Request the target directly so Cypress can verify the status code.
  cy.request(link.prop('href'));
});

This approach is simple, but it can be slow on large pages because every link becomes a network request. Scope the check to the content users actually read when you can.

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

That keeps the test useful without turning it into a long crawl of the entire page.

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