Back to articles

Automate Lighthouse Audits for Your Progressive Web App

Streamline Performance Testing with Mocha and Chai

June 29, 2019
Lighthouse audit automation dashboard showing performance metrics for a Progressive Web App
pwa
lighthouse
web development
3 min read

We all know how valuable and helpful the insights are from lighthouse audits when we’re developing our web applications. But the way most of us check is manually through Chrome dev tools or the lighthouse extension, which in my opinion, is not very productive.

For those of us who don’t know, there are mainly four ways of auditing our web application with lighthouse :

  • via Chrome dev tools

  • Command-line

  • NPM module ( which we are going to use in a while )

  • PageSpeed Insights


Dependencies

To programmatically perform lighthouse audits, we can use the lighthouse npm package, mocha, and chai for writing our tests and chrome-launcher for running our lighthouse tests.

First, let’s install the above packages as dev dependencies in our project :

npm install lighthouse chrome-launcher chai mocha --save-dev

Set up lighthouse

Now, let’s create a file named lighthouse.tests.js in our tests directory. We’ll run our lighthouse audits through this file. Here, we’ll import the lighthouse module and chrome launcher that helps us to open our webpage from the local development server and run the audits to test against a minimum threshold that we want our lighthouse scores to be.

While this might sound a lot to do, it isn’t much. Here’s what it looks like on actual code :

const lighthouse = require("lighthouse");
const chromeLauncher = require("chrome-launcher");

function launchChromeAndRunLighthouse(url, opts, conf = null) {
  return chromeLauncher
    .launch({ chromeFlags: opts.chromeFlags })
    .then((chrome) => {
      opts.port = chrome.port;
      return lighthouse(url, opts, conf).then((res) =>
        chrome.kill().then(() => res.lhr)
      );
    });
}

And it is as simple as that. We launch the chrome browser instance with the chromeLauncher.launch method and then run lighthouse tests with the site URL and configuration for our audits. After that, we close/kill the chrome instance and return the results. And this is how it looks like when in use :

launchChromeAndRunLighthouse(testUrl, opts, config).then((res) => {
  // Results are available in `res`
});

Write the tests

So now, we can put this call inside our before hook for the tests and then have tests for each metric, something like this :

describe("Lighthouse Audits", function () {
  // Timeout doesn't need to be same. It can be more or less depending on your project.
  this.timeout(50000);
  let results;
  before("run test", (done) => {
    launchChromeAndRunLighthouse(testUrl, opts, config).then((res) => {
      // Extract the results you need for your assertions.
      done();
    });
  });
  it("performance test", (done) => {
    // test your performance score against the threshold
    done();
  });
  // Some more tests..
});

Still looks weird? Don’t worry! Check out this repository for an example setup of lighthouse tests with mocha and try that out with your web application!

This method can be applied to automate the tests in continuous integration/deployment environments so that you don’t have to worry about manually auditing your web application and checking whether it meets the minimum satisfactory levels.


So there you go. That’s all we need to do for automating lighthouse audits for our progressive web applications to make sure they are always worthy of the internet and user’s data packets!

Atleast the Son of Odin is happy about his light house tests.


Did you like this article? Or did I miss something? Is there something that you have that can make it even better? Please leave a comment below, or you can also contact me through my social media profiles.

Thank you for reading! 😄


Happy hacking! Cheers! 🎉

You may also be interested in

Like any other web application, React applications also require close attention to their architecture. Introduction of Hooks might have shown us new ways of abstractions in our React applications but what about so many applications that are still using older versions of React?

Scalable React Application Architecture: Best Practices for Directory Structure

April 11, 2019

Learn how to structure your React applications with a scalable and maintainable architecture. Discover practical directory organization patterns based on real-world experience.

Read article
A visual guide to organizing complex React applications with Redux, Sagas, and Services for better state management and code maintainability

Redux Store Architecture in React Applications - Organizing Complex State Management

May 11, 2019

Learn how to architect complex React applications with Redux, Redux-Saga, and service layers. This guide provides a scalable structure for organizing reducers, actions, middlewares, and selectors in large React projects.

Read article
JSON-LD structured data implementation example with code and rich search result preview

JSON-LD for SEO: Boost Your Website's Search Visibility

February 14, 2024

Learn how to use JSON-LD structured data to enhance your website's SEO, improve rich snippets, and help search engines better understand your content.

Read article
React hooks implementation for state management without Redux

Managing React application state - without using Redux!

May 19, 2019

In this article, we explore managing React application state using hooks. We leverage the React.useContext and React.useReducer hooks to create a Redux-like state management system without external dependencies.

Read article
HTML code showing Microdata and Microformats implementation with semantic markup highlighted

Microdata & Microformats: Essential SEO Markup for Web Developers

November 19, 2023

Learn how to implement Microdata and Microformats to improve your website's SEO, help search engines understand your content, and increase visibility in search results.

Read article
SEO checklist with checkmarks and optimization elements for web developers

The Complete SEO Checklist for Web Developers in 2023

July 29, 2023

A comprehensive, actionable SEO checklist for web developers covering titles, meta descriptions, structured data, and technical optimizations to improve search rankings.

Read article