Share via


Integrating Angular Unit Tests With Visual Studio Team Services (VSTS) Using Headless Chrome and Puppeteer

In a previous post I showed you how to Integrate Angular Unit Tests with Visual Studio Team Services (VSTS). Whereas it worked flawlessly it did have dependency on PhantomJS which is a headless browser. The only issue with PhantomJS is that it tends to have some random issues which makes it challenging to integrate within your CI server. Fortunately, Chrome added support for running in headless mode starting with version 59. Thus, you can use headless Chrome to replace PhantomJS.

Start by modifying the Karma.conf.js file and set the browsers property to ChromeHeadless:

 browsers: ["ChromeHeadless"]

Remember to remove the npm packages related to phantomjs from your package.json file as they are not required anymore:

 "karma-phantomjs-launcher": "1.0.4",
"phantomjs-prebuilt": "^2.1.16",

Also remove the karma module from your karma.conf.js file:

 require("karma-phantomjs-launcher")

Although we are discussing unit tests in this post I will throw a bonus tip and help you modify the end to end tests to utilize Chrome headless as well. You need to modify the protractor.conf.js file capabilities object to include a chromeOptions property:

 "capabilities: {
    'browserName': 'chrome',
    chromeOptions: {
      args: [ "--headless", "--disable-gpu", "--window-size=800x600" ]
    }
  },

At this point you should be able to successfully run your unit tests (and e2e tests) successfully on your CI server. One challenge that arises from using Chrome though is that it needs to be installed globally which can be a bit tricky when using a CI server. Fortunately, there is a project called Puppeteer which is a node library that provides a high-level API to control headless Chrome over the DevTools Protocol. In addition, Puppeteer has an internal module that downloads and installs Chromium (not Chrome as it requires you to accept a License Agreement during installation which requires administrative privileges which in turn defeats the whole purpose of having a local installation). Install it using the following command:

 npm install --save-dev puppeteer

Next you will need to place the following code under your karma.conf.js file:

 process.env.CHROME_BIN = require('puppeteer').executablePath()

That's it. You should now be able to run your unit tests using headless Chrome and utilize Puppeteer to install Chrome on your CI server.