Surfer, Software Engineer, Open-sourcerer. Not necessarily in that order. Creator of http.cat.

Sep 14, 2017

Automating Karma and headless Chrome with Puppeteer

If you want to configure karma to use headless Chrome in a completely automated way without a global install of Chrome, this post is for you.

Google recently released Puppeteer, a node library that provides a high-level API to control headless Chrome over the DevTools Protocol. This alone is already pretty awesome. But there’s a hidden gem in this package: an internal module that downloads and installs Chromium locally.

We can use this module to overcome one of the issues we find when trying to replace the PhantomJS with headless Chrome: The fact that Chrome needs to be installed globally. This is a headache, specially if you’re trying to run your tests in a Continuous Integration environment and want to have every dependency contained in your project.

Now, I might have lied a little bit. We’re not going to use Chrome for this. We’re going to use Chromium. Why Chromium and not Chrome? Because Google Chrome requires you to accept a License Agreement on install, and that requires administration privileges which would defeat the whole purpose of having a local installation. In terms of running your tests, this shouldn’t have any relevant difference.

Fill in the rest of your karma configuration, and you should be ready to go.

Is there a cleaner way?

This is an undocumented API and this solution is considered a hack because it relies on an internal API that can change at any moment without notice. Puppeteer 0.11.0 will introduce an official and documented way to get Chromium’s executable path: puppeteer.executablePath(). Check the project’s documentation for more details.