This article is a step-by-step guide for adding PhantonJS to an Angular4+ application. This guide will walk through the process of generating a new Angular application, configuring PhantomJS in the Karma test runner, and finally executing the unit tests.

Prerequisites

This guide has the following prerequisites:

Node.js 8.0.0 (or greater)

NPM 5.0.0 (or greater)

Angular CLI 1.4.0 (or greater)

This tutorial assumes that npm is configured as the default package manager. If you need to change the package manager setting then use this command:

ng set --global packageManager=npm

Step 1: Generate a Project Using Angular CLI

Use the command line interface (CLI) for Angular to generate a new Angular project. The Angular CLI tool will create a working Angular application, an initial set of Jasmine tests, and the configuration for some of the basic tools needed for development (NPM, Karma, tslint, etc). As an example, the following command will generate a project in the current directory called 'dragon':

ng new dragon

Step 2: Add PhantomJS dependency

The karma-phantomjs-launcher enables the karma test runner to launch and interact with PhantomJS. Use NPM to install the karma-phantomjs-launcher package as a dev dependency by executing the following command in the root of the project:

npm install karma-phantomjs-launcher --save-dev

Note that PhantomJS is a dependency of the karma-phantomjs-launcher so it doesn't need to be explicitly installed as a dependency in your application.

Step 3: Add Intl Polyfill Dependency

The intl polyfill needs to be installed as an npm dependency. This polyfill enables PhantomJS to support the ECMAScript Internationalization API (also known as Standard ECMA-402). Run the following command to install the intl package:

npm install intl --save

The ECMAScript Internationalization API is natively supported by most modern browsers so this dependency is typically only needed for PhantonJS and some older browsers.

Step 4: Enable Shims and Pollyfills

Within the project, modify the 'src/polyfill.ts' to enable ECMAScript Internationalization API polyfills and the ECMAScript 6 shims.

Add the import for the ECMAScript 6 shims (i.e. import 'core-js/client/shim';). See line 44 in the example below.

Uncomment the line containing the import for 'intl.' See line 68 in the example below.

Step 6: Run the tests

By default, projects generated by Angular CLI will already have Jasmine tests defined (see src/app/app.component.spec.ts). We can run these tests to validate our configuration by issuing the following command:

npm run test

Summary

This guide provides the necessary steps for configuring Karma to use PhantomJS within an Angular project. These changes are simple but can have a huge impact on making the build process flexible and more performant.