Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

Cypress & Lighthouse Performance Testing Guide

· 4 min read · Home Tech

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

This guide shows you how to combine Cypress end-to-end tests with Google Lighthouse performance audits. You'll learn to automate performance checks as part of your test suite, catch regressions early, and get actionable metrics like Lighthouse Performance score, Largest Contentful Paint (LCP), and Cumulative Layout Shift (CLS). By the end, you'll have a repeatable setup that runs in your CI pipeline.

What You'll Need

  • Node.js (v18 or later) and npm installed
  • A basic Cypress project (or create one with npm init and npm install cypress --save-dev)
  • Google Chrome browser (Lighthouse uses Chrome)
  • Basic familiarity with JavaScript and Cypress commands

Step-by-Step

  1. Install the Lighthouse Cypress plugin. Run npm install --save-dev @cypress-audit/lighthouse. This plugin lets you run Lighthouse audits directly inside Cypress tests.
  2. Configure Cypress to use the plugin. In your cypress.config.js file, add the following:
    const { lighthouse, prepareAudit } = require('@cypress-audit/lighthouse');
    
    module.exports = defineConfig({
      e2e: {
        setupNodeEvents(on, config) {
          on('before:browser:launch', (browser, launchOptions) => {
            prepareAudit(launchOptions);
          });
          on('task', {
            lighthouse: lighthouse(),
          });
        },
      },
    });
  3. Write a performance test. Create a spec file like cypress/e2e/performance.cy.js. In it, use cy.lighthouse() to run the audit on the current page:
    describe('Performance audit', () => {
      it('should pass the Lighthouse performance budget', () => {
        cy.visit('https://example.com');
        cy.lighthouse({
          performance: 90,
          'largest-contentful-paint': 2500,
          'cumulative-layout-shift': 0.1,
        });
      });
    });
    The thresholds are optional; if omitted, the audit just runs and logs results.
  4. Run the test. Execute npx cypress run in your terminal. The plugin will launch Chrome, run the page, and generate a Lighthouse report. The test passes if all thresholds are met.
  5. View the report. After the run, look in the cypress/reports folder (or the path you configured) for an HTML report. You can also see the numeric scores in the Cypress command log.
  6. Integrate into CI. Add the same npx cypress run command to your CI pipeline (e.g., GitHub Actions, GitLab CI). Use the thresholds to fail the build if performance drops.

Common Mistakes

  • Forgetting to call prepareAudit in the browser launch hook. Without it, Lighthouse won't attach correctly and the audit will fail or be inaccurate.
  • Running against a production URL with dynamic content. If the page content changes between runs, scores will vary. Use a stable test environment or mock network responses.
  • Setting thresholds too strict for a dev environment. Development builds are often slower; set reasonable thresholds or run against a production build.
  • Ignoring the “mobile” vs “desktop” difference. By default, Lighthouse runs in mobile emulation. If you need desktop metrics, pass formFactor: 'desktop' in the options.
  • Not cleaning up before each audit. Previous test state can affect performance. Use cy.clearCookies() or cy.reload() before the audit if needed.

Tips

  • Run audits on critical pages only. Full Lighthouse audits are slow (5-10 seconds each); don't run them on every route in your suite.
  • Use Lighthouse CI for deeper analysis. If you need historical trends and budget comparisons, consider using @lhci/cli alongside Cypress.
  • Combine with Cypress's own performance timings. Use cy.clock() and cy.tick() to simulate user waits and measure interactions.
  • Set a custom Lighthouse config. You can pass a full Lighthouse config object to cy.lighthouse() to disable unused audits (e.g., SEO) and speed things up.
  • Store baseline scores. Save the results to a JSON file in CI and compare them to previous runs to detect regressions.

Troubleshooting

  • “Lighthouse is not defined” error. Make sure the plugin is installed and the task is registered correctly in setupNodeEvents. Restart Cypress after changing the config.
  • Audit fails with a timeout. Increase the default timeout in cy.lighthouse() by passing timeout: 60000 in the options. Also ensure the page loads within the test's defaultCommandTimeout.
  • Results vary wildly between runs. This is normal for Lighthouse; it's affected by network and CPU. Run the audit 3 times and take the median, or use a throttling preset like throttling: 'mobile' to standardize.
  • Chrome not launching in CI. Install Chrome in your CI environment and set the CHROME_PATH environment variable if needed. Also ensure you're using the electron or chrome browser in Cypress.
  • Plugin doesn't work with Firefox. The plugin only supports Chrome/Chromium. Use cy.lighthouse() only when running in Chrome.

Frequently Asked Questions

Can I run Lighthouse audits on multiple pages in one test?

Yes, you can call cy.lighthouse() after each cy.visit(). Just be aware that each audit takes time, so keep the number of pages reasonable.

Does this work with Cypress Component Testing?

No, the plugin is designed for end-to-end tests. For component-level performance, use React DevTools Profiler or similar.

How do I get a Lighthouse report file?

By default, the plugin writes an HTML report to cypress/reports/lighthouse. You can also access the raw JSON result in the test via cy.lighthouse().then((results) => ...).

Can I use this with a login-required page?

Yes, perform the login in Cypress first (e.g., cy.login()), then run the audit. The cookies and session will be preserved.

What is the difference between this and Lighthouse CI?

This plugin runs audits within your Cypress test flow, which is great for quick feedback. Lighthouse CI is a separate tool that provides a dashboard, budget comparisons, and historical trends. You can use both together.

Why is my performance score lower than in Chrome DevTools?

The plugin runs Lighthouse in mobile emulation by default, which is stricter. Also, your test environment may have different network conditions. Use the same throttling settings to compare apples to apples.