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 :
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`});
Writing the Audit Tests with Mocha and Chai
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.
Conclusion
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!
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! 🎉
Continue Reading
Discover more insights and stories that you might be interested in.