DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workkloads.

Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How to Effortlessly Host Your Angular Website on GitHub Pages
  • Keep Your Application Secrets Secret
  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Legacy Code Refactoring: Tips, Steps, and Best Practices

Trending

  • Building a Simple Todo App With Model Context Protocol (MCP)
  • From Fragmentation to Focus: A Data-First, Team-First Framework for Platform-Driven Organizations
  • Article Moderation: Your Questions, Answered
  • AI-Assisted Coding for iOS Development: How Tools like CursorAI Are Redefining the Developer Workflow
  1. DZone
  2. Coding
  3. Frameworks
  4. Using PhantomJS With Karma

Using PhantomJS With Karma

In this article, a developer provides the necessary steps for configuring Karma to use PhantomJS within an Angular project.

By 
Chet Rogers user avatar
Chet Rogers
·
Dec. 24, 17 · Tutorial
Likes (4)
Comment
Save
Tweet
Share
30.7K Views

Join the DZone community and get the full member experience.

Join For Free

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.

  1. Add the import for the ECMAScript 6 shims (i.e. import 'core-js/client/shim';). See line 44 in the example below.
  2. Uncomment the line containing the import for 'intl.' See line 68 in the example below.
/**
 * This file includes polyfills needed by Angular and is loaded before the app.
 * You can add your own extra polyfills to this file.
 *
 * This file is divided into 2 sections:
 *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.
 *   2. Application imports. Files imported after ZoneJS that should be loaded before your main
 *      file.
 *
 * The current setup is for so-called "evergreen" browsers; the last versions of browsers that
 * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),
 * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.
 *
 * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html
 */

/***************************************************************************************************
 * BROWSER POLYFILLS
 */

/** IE9, IE10 and IE11 requires all of the following polyfills. **/
// import 'core-js/es6/symbol';
// import 'core-js/es6/object';
// import 'core-js/es6/function';
// import 'core-js/es6/parse-int';
// import 'core-js/es6/parse-float';
// import 'core-js/es6/number';
// import 'core-js/es6/math';
// import 'core-js/es6/string';
// import 'core-js/es6/date';
// import 'core-js/es6/array';
// import 'core-js/es6/regexp';
// import 'core-js/es6/map';
// import 'core-js/es6/weak-map';
// import 'core-js/es6/set';

/** IE10 and IE11 requires the following for NgClass support on SVG elements */
// import 'classlist.js';  // Run `npm install --save classlist.js`.

/** Evergreen browsers require these. **/
import 'core-js/es6/reflect';
import 'core-js/es7/reflect';
import 'core-js/client/shim';

/**
 * Required to support Web Animations `@angular/platform-browser/animations`.
 * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation
 **/


// import 'web-animations-js';  // Run `npm install --save web-animations-js`.
/***************************************************************************************************
 * Zone JS is required by Angular itself.
 */
import 'zone.js/dist/zone';  // Included with Angular CLI.



/***************************************************************************************************
 * APPLICATION IMPORTS
 */

/**
 * Date, currency, decimal and percent pipes.
 * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10
 */
 import 'intl';  // Run `npm install --save intl`.
/**
 * Need to import at least one locale-data with intl.
 */
// import 'intl/locale-data/jsonp/en';

Step 5: Enable PhantomJS for Karma

Each project generated with the Angular CLI will include the configuration for the Karma test runner (i.e. karma.conf.js). Modify the karma.conf.js so that...

  1. Karma uses the karma-phamtaomjs-launcher plugin (see line 13 in the example below).
  2. Karma uses the PhantomJS as the browser to be launched (see line 32 in the example below).
  3. Karma shuts down after all tests have run (see line 33 in the example below).
// Karma configuration file, see link for more information
// https://karma-runner.github.io/1.0/config/configuration-file.html

module.exports = function (config) {
  config.set({
    basePath: '',
    frameworks: ['jasmine', '@angular/cli'],
    plugins: [
      require('karma-jasmine'),
      require('karma-chrome-launcher'),
      require('karma-jasmine-html-reporter'),

      require('karma-phantomjs-launcher'),
      require('karma-coverage-istanbul-reporter'),
      require('@angular/cli/plugins/karma')
    ],
    client:{
      clearContext: false // leave Jasmine Spec Runner output visible in browser
    },
    coverageIstanbulReporter: {
      reports: [ 'html', 'lcovonly' ],
      fixWebpackSourcePaths: true
    },
    angularCli: {
      environment: 'dev'
    },
    reporters: ['progress', 'kjhtml'],
    port: 9876,
    colors: true,
    logLevel: config.LOG_INFO,
    autoWatch: true,
    browsers: ['PhantomJS'],
    singleRun: true
  });
};

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.

Command-line interface AngularJS Testing

Opinions expressed by DZone contributors are their own.

Related

  • How to Effortlessly Host Your Angular Website on GitHub Pages
  • Keep Your Application Secrets Secret
  • React, Angular, and Vue.js: What’s the Technical Difference?
  • Legacy Code Refactoring: Tips, Steps, and Best Practices

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!