By default, Chrome is set as the test runner of choice for applications generated with Angular-cli. The problem is that Chrome is really slow for running more than a few tests.
For anyone who develops following the Test Driven Development(TDD) approach like myself, this can be extremely annoying. If you have anything more than a few test cases, you could pretty much drink whole cup of coffee while waiting for tests to complete after each save.
Long story short, if you are working on a mature codebase with tens, hundreds or even thousands of test cases, Chrome is not a sustainable choice for TDD.
In the past, this problem could be solved by replacing Chrome with PhantomJS as the browser of choice for running unit tests via Karma. Fast forward to 2017 with most front end frameworks running Typescript or ES2015 and this becomes a problem.
PhantomJS 2.1.x Does Not Support ES2015
Whether you are building your app in ES2015 or transpiling to ES2015 from Typescript, you will have problems running your tests on anything less than PhantomJS 2.5 because ES2015+ syntax is not recognized.
Step 1: Install PhantomJS 2.5 Beta
Installation Instructions:
Step 2: Add Karma PhantomJS Launcher to Your Package Development Dependencies
For this article, I built a quick project with the latest version of Angular-cli. This step should be pretty easy to adjust for other frameworks where you are running Karma.
Since we are invoking the test runner via npm run test
, all we have to do is add the karma-phantomjs-launcher and update a couple of lines in the karma.conf.js file.
SIDEBAR: Anything you run from the scripts block of your package.json file runs within the context of your project’s node_modules/ directory. If you wanted to execute anything in your project’s node_modules directory from outside of your package.json scripts file, you would have to reference with the fully qualified path.
Install the karma-phantomjs-launcher by running from the root of your project’s directory: npm install --save-dev karma-phantomjs-launcher
.
After installing the karma-phantomjs-launcher, update your karma.conf.js file:
- Change the line
require('karma-chrome-launcher')
torequire('karma-phantomjs-launcher')
- Change the line in browsers
['Chrome']
to['PhantomJS']
For convenience, I added my sample project to Github. You can find a diff of the changes here:
https://github.com/ryanmccormick/angular2-karma-phantomjs-testing/compare/chrome…phantomjs
Leave a Reply