Setting Up Angular CLI for Headless Chrome Testing

Headless Chrome offers a practical way to execute automated tests when launching a full browser isn’t viable. This guide walks through configuring Angular CLI so that both Unit and E2E Tests can run on Headless Chrome.

This setup is essential for the upcoming pieces in The Angular DevOps Series, where running automated tests within a Continuous Integration pipeline is a requirement.

Installation Steps

Angular CLI conveniently includes karma-chrome-launcher as one of the devDependencies in package.json. Consequently, no additional packages are needed to incorporate Headless Chrome into your testing workflow.

Running Unit Tests

The standard npm run test command enables watch mode, where the unit tests re-run after any code changes. For a continuous integration scenario, though, we need a script that executes the tests one time and terminates. To achieve this, add a new entry in the scripts object within package.json — let’s call it test-headless:

"scripts": {
  "ng": "ng",
  "start": "ng serve",
  "build": "ng build",
  "test": "ng test",
  "test-headless": "ng test --watch=false --browsers=ChromeHeadless",
  "lint": "ng lint",
  "e2e": "ng e2e"
},

Take note of the following flags:

  • --watch=false
    Instructs the tests to run a single time and then exit, preventing any file watching.
  • --browsers=ChromeHeadless
    Designates Headless Chrome as the browser used for executing the tests.

Execute the unit tests in headless mode with:

npm run test-headless

Running E2E Tests

When scaffolding a new workspace, Angular CLI sets up Protractor to handle End-to-End (E2E) testing.

Configuring E2E tests to use Headless Chrome requires more effort than just updating a script, because ng e2e only accepts certain options that don’t map directly to Protractor’s native command-line flags. The solution is to adjust the Protractor configuration file instead.

The relevant configuration file for your E2E tests is located at:
e2e/protractor.conf.js

In this file, update the capabilities section with a chromeOptions object as demonstrated:

capabilities: {
  chromeOptions: {
    args: [ "--headless" ]
  },
  'browserName': 'chrome'
},

Within chromeOptions, the args property accepts an array of string values passed to Protractor. For basic headless operation, a single argument is sufficient:

  • --headless
    Enables Chrome’s headless mode.

That’s the simplest setup to get E2E tests running. However, if your code depends on certain browser characteristics — such as viewport dimensions — you might add extra flags, e.g., --window-size=800x600.

Launch your E2E tests with:

npm run e2e