Last Updated: February 25, 2016
·
4.978K
· rhysr

Angular Testing Setup

Quick start for setting up testing with angular, karma and jasmine. Follows on this guide

Packages

First globally install the relevant testing packages

npm install -g karma jasmine-node phantomjs
  • karma is the test runner
  • jasmine is the test framework
  • phantomjs allows testing without opening a real browser

NVM USERS

If you are an nvm user, you'll need to set up an environment variable for the phantomJs binary, my solution was to add the following to bottom of my ~/.zshrc (should work for ~/.bashrc)

export PHANTOMJS_BIN=$NVM_BIN"/phantomjs"

Setup

Create directory for all our test configurations

mkdir configs

Create directory for our unit tests

mkdir -p test/unit

Get all angular files

mkdir -p {public/app,test}/lib/angular

curl http://code.angularjs.org/1.0.7/angular.min.js > public/app/lib/angular/angular.min.js

curl http://code.angularjs.org/1.0.7/angular-mocks.js > test/lib/angular/angular-mocks.js

Then we need to generate a karma config script for our unit tests

karma init configs/karma.conf.js

You will then get a load of questions which you'll need to respond to like this

  • testing framework: jasmine (default)
  • require.js: no (default)
  • Browser: PhantomJS (press tab to cycle through options)
  • files to test
    • public/app/lib/angular/angular.min.js
    • test/lib/angular/angular-mocks.js
    • public/app/*.js
    • test/unit/*Spec.js
  • Testacular watch: yes

Then we can start karma monitoring for our tests

karma start configs/karma.conf.js

Now we are ready to create our first test class

test/unit/controllerSpec.js

'use strict';

describe('IndexController', function() {
    //initialise module
    beforeEach(module('myapp.controllers'));

    //params initialised in scope for tests
    var ctrl, scope;

    beforeEach(inject(function($controller) {
        //get controller from $controller provider
        scope = {}; 
        ctrl = $controller('IndexController', {
            $scope: scope
        }); 
    }));

    it ('should add name parameter to scope', function() {
        expect(scope.name).toBeDefined(); 
    }); 
});

After saving this file, we should see the controllerSpec.js file get picked up by karma and added to the test suite. It should start failing as scope has no name element

To make test test pass open public/app/controllers.js add the following to IndexController

$scope.name = 'bob';

and you'll see karma report the tests pass.