<img height="1" width="1" style="display:none;" alt="" src="https://dc.ads.linkedin.com/collect/?pid=1005900&amp;fmt=gif">

Insights

Integrating Lighthouse into Cypress Testing: A Guide to Performance & Accessibility Audits

Why Integrate Lighthouse into Cypress?

In modern web development, automated testing isn’t just about verifying functionality—it also extends to performance, accessibility, and SEO. Google’s Lighthouse is a powerful tool that provides audits for these crucial aspects, ensuring web applications meet best practices. By integrating Lighthouse into Cypress, developers can automate these audits within their end-to-end testing workflows, catching issues before they reach production.

Key Benefits of Lighthouse in Cypress:

  • Performance Optimisation – Identify bottlenecks and improve site speed.
  • Accessibility Compliance – Ensure websites are usable for all users.
  • SEO Enhancements – Validate proper metadata, structured data, and best practices.
  • Best Practices & Progressive Web App (PWA) Checks – Maintain web standards and progressive features.

Setting Up Lighthouse in Cypress

To integrate Lighthouse with Cypress, we’ll use the cypress-audit plugin, which allows running Lighthouse audits within Cypress tests.

Prerequisites:

  • A Cypress project set up (if you haven’t, initialize one with npm init cypress or npx cypress open)
  • Node.js installed
  • Lighthouse and Cypress Audit plugin

Installation

Run the following command to install the necessary dependencies:

Installation

Run the following command to install the necessary dependencies:

npm install -D cypress-audit

 

Configuring Cypress to Use Lighthouse

Modify your Cypress cypress.config.ts (or cypress.config.js for JavaScript projects) to include the Lighthouse integration:

const { lighthouse, prepareAudit } = require("@cypress-audit/lighthouse");

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on("task", {
        lighthouse: lighthouse(),
      });
    },
  },
});

Writing a Cypress Test with Lighthouse

Now, let’s create a test that runs a Lighthouse audit on a sample page:

describe("Lighthouse Performance Test", () => {
  it("should pass Lighthouse audits", () => {
    cy.visit("https://example.com");
    cy.lighthouse({
      "performance": 90,
      "accessibility": 90,
      "best-practices": 90,
      "seo": 90,
    });
  });
});

Breaking Down the Test:

  • cy.visit("https://example.com") navigates to the target website.
  • cy.lighthouse({...}) runs Lighthouse audits and enforces minimum scores (90 in this example).

Running the Test

Execute the Cypress test suite with:

npx cypress run

This will run the Lighthouse audit alongside your functional tests.

Customizing Lighthouse Audits

You can tweak the Lighthouse configuration by passing options:

cy.lighthouse({
  performance: 85,
  accessibility: 95,
  "best-practices": 80,
  seo: 90,
}, {
  formFactor: "desktop", // or "mobile"
  screenEmulation: { disabled: true },
});

Further Custom Configurations

For advanced use cases, additional customization can be implemented:

Saving Results to JSON

To save Lighthouse reports dynamically, you can modify Cypress tasks to store reports with custom names:

on('task', {
  setLighthouseReportName: (name) => {
    lighthouseReportName = name;
    return null; 
  },

  lighthouse: lighthouse((lighthouseReport) => {
    const folderPathForLH = 'cypress/lightHouse';
    if (!fs.existsSync(folderPathForLH)) {
      fs.mkdirSync(folderPathForLH, { recursive: true });
    }
    const filePath = `${folderPathForLH}/${lighthouseReportName}.json`;
    fs.writeFileSync(filePath, JSON.stringify(lighthouseReport, null, 2));
  })
})

Then in your tests where you might be running several reports in one journey you can first name the transaction then call the lighthouse command as such:

cy.task('setLighthouseReportName', 'Homepage') //Name Scenario
  .then(() => {
    cy.lighthouse();
  })

This configuration ensures that each Lighthouse audit report is stored uniquely, facilitating historical tracking and comparisons.

 

Understanding Your Lighthouse Report

Once you have run a Lighthouse audit within Cypress, the results will be saved as a JSON file. Understanding the different sections of the Lighthouse report is crucial for improving your application's performance and compliance.

Each section provides a score out of 100 and detailed recommendations to improve your website. By analysing and acting on these insights, you can ensure your application is optimised for both users and search engines.

More detailed info can be found here : https://developer.chrome.com/docs/lighthouse/overview

 

Conclusion

Integrating Lighthouse into Cypress ensures that performance, accessibility, and best practices are continuously tested. This automation helps developers catch regressions early and maintain high-quality web applications. By running Lighthouse audits as part of your CI/CD pipeline, you can enforce standards and deliver a better user experience with every deployment.

 

Need help scaling your performance strategy?
Capacitas helps teams build scalable, high-performing web applications with integrated testing and optimisation. Get in touch if you want to know more https://www.capacitas.co.uk/book-a-diagnostic-session

 

 

  • There are no suggestions because the search field is empty.