AngularJS - Testing Overview

The initial setup:

<div ng-app="myApp">
  <div ng-controller="FirstCtrl">
    <input type="text" ng-model="data.message">
    <h1>{{ data.message }}</h1>
  </div>
  <div ng-controller="SecondCtrl">
    <input type="text" ng-model="data.message">
    <h1>{{ data.message   reverse }}</h1>
  </div>
</div>
var myApp = angular.module('myApp', []);

myApp.factory('Data', function () {
  return { message: "I'm data from a service" }
});

myApp.filter('reverse', function () {
  return function (text) {
    return text.split("").reverse().join("");
  }
}

function FirstCtrl($scope, Data) {
  $scope.data = Data;
}

function SecondCtrl($scope, Data) {
  $scope.data = Data;
} 

Note: This example uses the Karma test runner with Jasmine testing framework, taken from the angular-seed app.

Writing a filter unit test

The karma.conf.js file is pointed at the mainSpec.js unit test file, and we’re ready to write a unit test.

describe('filter', function () {
  beforeEach(module('myApp'));

})

This sets up a filter test suite in which the unit tests will reside. Since we are testing filters, these are accessed within the myApp AngularJS app, and so we must bring this module into the test suite.

Within the filter suite, we start writing the reverse filter test, and state the description of a well-behaved test. In order to test the filter, it needs to be injected into the test.

describe('filter', function () {
  beforeEach(module('myApp'));

  describe('reverse', function () {
    it('should reverse a string', inject(function (reverseFilter) {

    }))
  })
})

Now we can begin to write the test logic, here using the expect() method.

describe('reverse', function () {
    it('should reverse a string', inject(function (reverseFilter) {
      expect(reverseFilter('ABCD')).toEqual('DCBA');
    }))
  })