Automating System Page Navigation and Broken Link Validation Using Cypress

Mohamed Said Ibrahim
5 min readOct 1, 2024

--

As businesses increasingly rely on systems to streamline processes, maintaining the health of these systems becomes paramount. One essential aspect is ensuring that every page and link works correctly and that the system’s UI components behave as expected. Cypress, a powerful end-to-end testing framework, can help automate the process of navigating through all pages, checking for broken links, and gathering data on page components.

In this article, we will walk through creating a Cypress test that automates:

• Opening all system pages

• Validating that all links on those pages are functional (no broken links)

• Extracting useful data about the UI components (buttons, inputs, text areas, etc.)

• Saving this information for further analysis

By the end of this tutorial, you’ll have a fully functional Cypress setup for system testing, complete with code snippets for easy integration.

Prerequisites

To follow along with this guide, you need:

• Basic understanding of Cypress and JavaScript

• A running system with a list of pages to check

• Node.js and npm installed on your machine

Getting Started: Setting Up Cypress

Install Cypress
First, ensure you have Cypress installed in your project. If it’s not already installed, run:

npm install cypress - save-dev

Install axios for HTTP Requests
To validate links on the pages, we will use axios to handle HTTP requests:

npm install axios

Install Cypress File Upload Plugin
We’ll also install the cypress-file-upload plugin to easily save component data to files.

npm install cypress-file-upload

Creating Custom Cypress Commands

We’ll create two custom commands: one to check all the links on a page and another to extract component data from the page. These commands will be added to Cypress’s commands.ts file.

Check Page Links

This command will find all the anchor (<a>) tags on the page, extract their href attributes, and make a request to validate the link’s status.

// cypress/support/commands.ts

declare namespace Cypress {
interface Chainable<Subject = any> {
/**
* Custom command to check for broken links on a page and return an array of broken links.
* @param brokenLinks - Callback function to process the broken links
*/
checkPageLinks(): Chainable<Array<LinkIssue>>;
}
}

// Define the type for the broken links
interface LinkIssue {
link: string;
status: number;
}

// Define the Cypress command
Cypress.Commands.add('checkPageLinks', (): Cypress.Chainable<Array<LinkIssue>> => {
const linksWithIssues: Array<LinkIssue> = [];

cy.get('a').each((link) => {
const href = link.prop('href');
if (href) {
cy.request({ url: href, failOnStatusCode: false }).then((response) => {
if (response.status < 200 || response.status >= 400) {
linksWithIssues.push({ link: href, status: response.status });
}
});
}
}).then(() => {
// Return the array of broken links
return cy.wrap(linksWithIssues);
});
});

Extract Component Data

This command will scrape data from buttons, inputs, text areas, and other UI components on the page, then save the data to a JSON file.

// cypress/support/commands.ts

Cypress.Commands.add('extractComponentsData', (pageUrl: string, brokenLinks: Array<any>, fileName: string) => {
const components = [];

// Collect all buttons, inputs, text areas, etc.
cy.get('button').each(($btn) => {
components.push({ type: 'button', text: $btn.text() });
});

cy.get('input').each(($input) => {
components.push({ type: 'input', name: $input.attr('name'), value: $input.val() });
});

cy.get('textarea').each(($textarea) => {
components.push({ type: 'textarea', name: $textarea.attr('name'), value: $textarea.val() });
});

cy.get('select').each(($select) => {
components.push({ type: 'select', name: $select.attr('name') });
});

const output = {
page: pageUrl,
brokenLinks: brokenLinks,
components: components
};

// Save data to file
cy.writeFile(`cypress/results/${fileName}.json`, JSON.stringify(output, null, 2));
});

Creating the Cypress Test

Now, we’ll create a Cypress test that:

• Logs into the system

• Visits each page

• Validates the links on the page

• Extracts and saves data on the page’s components

// cypress/integration/broken_links_spec.ts

describe('System - Broken Links and Component Data', () => {
const pages = [
'/dashboard',
'/accounts',
'/invoices',
'/orders',
// Add URLs for all the pages you want to check
];

beforeEach(() => {
cy.login(); // Assuming you have a login command
});

pages.forEach((page) => {
it(`should open ${page}, check links, and save components data`, () => {
cy.visit(page);

// Check for broken links and pass them to the extract function
cy.checkPageLinks().then((brokenLinks) => {
// Extract and save components data, along with the broken links and page URL
cy.extractComponentsData(page, brokenLinks, page.replace(/\//g, '_'));
});
});
});
});

Handling Authentication: Cypress Login Command

Systems are often behind login screens. To handle this, create a cy.login() command to log in to the system before visiting any pages:

// cypress/support/commands.ts
Cypress.Commands.add('login', () => {
cy.visit('/login');
cy.get('input[name="username"]').type('your-username');
cy.get('input[name="password"]').type('your-password');
cy.get('button[type="submit"]').click();
});

Make sure to replace the credentials and selectors with the ones that match your system’s login page.

Saving the Results

• Broken Link Check Results: Cypress will log each link validation in the test runner output.

• Component Data: For each page, a JSON file containing the page’s components will be saved in the cypress/results/ folder. Each file will be named based on the page’s URL.

Running the Tests

To run the test, simply use the Cypress CLI:

npx cypress run - spec cypress/integration/broken_links_spec.ts

Conclusion

In this tutorial, we have created a Cypress test suite that navigates through an system, checks for broken links, and extracts useful data about UI components. This automation can be easily extended or integrated into a CI/CD pipeline, providing a scalable solution for validating systems’ integrity.

By regularly running this test, you can ensure that your system is free of broken links and has correctly functioning UI components. It’s a proactive approach to maintaining system health and ensuring smooth operations for end users.

You have learnt :

“How to Automate Page Navigation and Broken Link Validation Using Cypress”

“End-to-End System Testing: Checking Broken Links and Extracting Component Data with Cypress”

“Using Cypress to Validate System Links and Gather UI Component Data”

“Automating System Page Validation: Detecting Broken Links and Analyzing Components with Cypress”

“Complete Guide to Cypress Automation for Systems: Checking Links and Extracting UI Data”

These titles are SEO-optimized to attract users searching for system testing, Cypress automation, and end-to-end test validation topics.

Buy me a Coffee

If you enjoy this content and want to support me, feel free to [buy me a coffee].

https://ko-fi.com/mohamedsaidibrahim

--

--

Mohamed Said Ibrahim
Mohamed Said Ibrahim

Written by Mohamed Said Ibrahim

Sharing actionable tips and best practices in test automation, Api Testing and Performance with tools like Cypress.io, Selenium, Postman,Playwright and K6..

Responses (3)