Testing AngularJS: Directives

So far in this series of AngularJS-related posts, we have looked at some utility factories for tracking web requests and preventing navigation requests, whether in-app or not, and how to write tests for those factories using Jasmine. In this post, we will look at how I generally test directives and how that impacts their structure.

Directives

Directives are the things we write in AngularJS that allow us to extend and modify the HTML language. We provide a template, some code-behind, and data binding, and AngularJS performs its magic to create a new behavior or control that is inserted via tag, attribute or CSS class. However, directives can at first seem difficult to test.

Let's look at a convoluted example.

sa.directive('saEditableField', function () {
    return {
        restrict: 'E',
		require: 'ngModel',
        template: '<label>{{fieldName}}</label><input type="text" ng-model="fieldValue" /><button ng-click="showField()">Alert!</button>',
        scope: {
            fieldName: '@saFieldName',
            fieldValue: '=ngModel'
        },
        controller: function($scope) {
            $scope.showField = function() {
                window.alert("Your " + $scope.fieldName + " is " + $scope.fieldValue);
            };
        }
    };
});

In this example we have a very simple directive. It specifies a template, some scope, and a controller where the business logic lives. It is used like this:

<sa-editable-field sa-field-name="First Name" ng-model="fieldValue"></sa-editable-field>

As it stands, there are a one or two things that either make this difficult to test or (I feel) could be clearer1. Let's refactor this directive with testing in mind.

Tests

When I have a working directive that I want to test, I tend to start writing tests. I realise this seems obvious, but it is worth noting as I do not tend to do much refactoring before writing tests and I don't tend to write tests before I have something to test. I find it much more useful to get a concept working and then think about what tests should be there and how I can implement those tests. When I find friction in authoring those tests, I identify my refactoring priorities.

Considering the directive presented above, what tests do we need? Here is the list of things that I think should be tested:

  • That the directive exists
  • That the directive compiles
  • That the alert shows when the button is clicked
  • That the alert mentions the field name
  • That the alert mentions the field value

Testing that the directive exists is easy (note that we have to add Directive to the end for the directive to be injected).

describe 'exists', ->
  When => inject (saEditableFieldDirective) =>
    @saEditableField = saEditableFieldDirective
  Then => expect(@saEditableField).toBeDefined()

Checking it compiles is a little more convoluted, but not difficult.

describe 'compiles', ->
  Given => inject ($rootScope) =>
    @scope = $rootScope.$new()
    @scope.field = 'test'
    @htmlFixture = angular.element('<sa-editable-field sa-field-name="Test" ng-model="field"></sa-editable-field>');
  When => inject ($compile) =>
    $compile(@htmlFixture)(@scope)
    @scope.$apply()
  Then => @htmlFixture.find('label').length == 1
  And => @htmlFixture.find('label').text() == 'Test'
  And => @htmlFixture.find('input').length == 1
  And => @htmlFixture.find('button').length == 1

The linking function that $compile returns is called because  $compile can succeed even if our fixture has a typo.

Using knowledge of our directive template, we can verify that the linking worked without going so far as to validate every aspect of the magic Angular does for us. In fact, since this is really intended to test the code that gets called inside the directive when it is linked to a scope, the template for the directive could be as simple as <div></div> (we will take a closer look in a future post at how we can make the directive template replaceable).

Testing the Alert

Testing that the directive exists, compiles and links is relatively straightforward when compared with testing that the alert is shown and shows the right thing. In order to test the alert, we need to be able to invoke showField, the method that shows it. We also need to check that showField actually shows the alert as we would like.

To invoke showField, we might try using the scope that is passed to the link method returned from $compile. Since the method is added to the scope in the controller, this should work, right? Of course not; this directive has an isolate scope and as such the method has been added to its own copy of the passed scope. We can get to that isolate scope from the compiled element using the isolateScope() method;

describe '#showField', ->
  Given => inject ($rootScope) =>
    @scope = $rootScope.$new()
    @scope.field = 'test'
    @htmlFixture = angular.element('<sa-editable-field sa-field-name="Test" ng-model="field"></sa-editable-field>');
  When => inject ($compile) =>
    $compile(@htmlFixture)(@scope)
    @scope.$apply()
  Then => expect(@htmlFixture.isolateScope().showFi

…but I feel like such a test involves too much setup ceremony just to get to the test2 and it relies on too many things outside of just the bit we want to validate. Instead, what if we could get at the controller independently of the directive?

sa.directive('saEditableField', function () {
    return {
        restrict: 'E',
		require: 'ngModel',
        template: '<label>{{fieldName}}</label><input type="text" ng-model="fieldValue" /><button ng-click="showField()">Alert!</button>',
        scope: {
            fieldName: '@saFieldName',
            fieldValue: '=ngModel'
        },
        controller: 'saFieldController'
    };
});

sa.controller('saFieldController', ['$scope', function($scope) {
    $scope.showField = function() {
        window.alert("Your " + $scope.fieldName + " is " + $scope.fieldValue);
    };
}]);

Now our controller is completely separate from the directive, which refers to the controller by name. This means we can write what I feel are clearer directive tests. Using a fake for the controller, we isolate the directive from the real thing and any side-effects it may have;

describe 'saEditableField', ->
  Given -> module ($provide) ->
    fakeFieldController = jasmine.createSpyObj 'saFieldController', ['showField']
    $provide.value 'saFieldController', fakeFieldController;return
  
  describe 'exists', ->
    When => inject (saEditableFieldDirective) =>
      @saEditableField = saEditableFieldDirective
    Then => expect(@saEditableField).toBeDefined()
      
  describe 'compiles', ->
    Given => inject ($rootScope) =>
      @scope = $rootScope.$new()
      @scope.field = 'test'
      @htmlFixture = angular.element('<sa-editable-field sa-field-name="Test" ng-model="field"></sa-editable-field>');
    When => inject ($compile) =>
      $compile(@htmlFixture)(@scope)
      @scope.$apply()
    Then => @htmlFixture.find('label').length == 1
    And => @htmlFixture.find('label').text() == 'Test'
    And => @htmlFixture.find('input').length == 1
    And => @htmlFixture.find('button').length == 1

…and now the controller can have its own tests too;

describe 'saFieldController', ->
  describe 'exists', ->
    Given => inject ($rootScope) =>
      @scope = $rootScope.$new()
    When => inject ($controller) =>
      @saFieldController = $controller 'saFieldController', { $scope: @scope }
    Then => expect(@saFieldController).toBeDefined()
      
  describe '#showField', ->
    describe 'exists', ->
      Given => inject ($rootScope) =>
        @scope = $rootScope.$new()
      When => inject ($controller) =>
        @saFieldController = $controller 'saFieldController', { $scope: @scope }
      Then => expect(@scope.showField).toEqual jasmine.any(Function)

$window

However, we are not quite finished. How do we know that the alert is shown when our showField method is called? We could spy on the global window object, but that's not really very Angular-y and our alert will get shown during testing (goodness knows what other side-effects we might face by using the global window object). What we need is an injectable version of window that we can replace with a fake during our tests. Not unsurprisingly, AngularJS has us covered with the $window service.

sa.controller('saFieldController', ['$scope', '$window', function($scope, $window) {
    $scope.showField = function() {
        $window.alert("Your " + $scope.fieldName + " is " + $scope.fieldValue);
    };
}]);

Now with our controller rewritten to use $window, we can tidy up and complete its test cases.

describe 'saFieldController', ->
  Given -> module ($provide) ->
    $provide.value '$window', jasmine.createSpyObj('$window', ['alert']);return
      
  describe 'exists', ->
    Given => inject ($rootScope) =>
      @scope = $rootScope.$new()
    When => inject ($controller) =>
      @saFieldController = $controller 'saFieldController', { $scope: @scope }
    Then => expect(@saFieldController).toBeDefined()
      
  describe '#showField', ->
    describe 'exists', ->
      Given => inject ($rootScope) =>
        @scope = $rootScope.$new()
      When => inject ($controller) =>
        @saFieldController = $controller 'saFieldController', { $scope: @scope }
      Then => expect(@scope.showField).toEqual jasmine.any(Function)
        
    describe 'calls $window.alert', ->
      Given => inject ($rootScope, $controller, $window) =>
        @scope = $rootScope.$new()
        @windowService = $window
        @saFieldController = $controller 'saFieldController', { $scope: @scope }
      When => @scope.showField()
      Then => expect(@windowService.alert).toHaveBeenCalled()
      
    describe 'alert includes $scope.fieldName', ->
      Given => inject ($rootScope, $controller, $window) =>
        @scope = $rootScope.$new()
        @scope.fieldName = "Test Name"
        @windowService = $window
        @saFieldController = $controller 'saFieldController', { $scope: @scope }
      When => @scope.showField()
      Then => expect(@windowService.alert.calls.mostRecent().args[0]).toMatch /.*Test Name.*/
        
    describe 'alert includes $scope.fieldValue', ->
      Given => inject ($rootScope, $controller, $window) =>
        @scope = $rootScope.$new()
        @scope.fieldValue = "Test Value"
        @windowService = $window
        @saFieldController = $controller 'saFieldController', { $scope: @scope }
      When => @scope.showField()
      Then => expect(@windowService.alert.calls.mostRecent().args[0]).toMatch /.*Test Value.*/

And there you have it. Some simple steps that make unit testing directives a little easier.

Finally…

In this post, we have taken a very brief look at how to structure a directive to simplify unit testing by separating the directive declaration from its controller and taking advantage of Angular services such as $window.

Although we have not covered some of the more complex directive concepts such as the link function and DOM manipulation3, these simple steps should take you a long way towards providing better test coverage of your AngularJS widgets.

Until next time, take care and don't forget to leave a comment.

  1. Not unexpected since I wrote it to discuss these things []
  2. we have to compile a fixture with a scope and then get the isolate scope from the element []
  3. I may cover that in a future post if there is interest or the whim takes me []

Navigation guard using AngularJS: $locationChangeStart

Where were we?

In the last post, I introduced saNavigationGuard, an AngularJS factory that provided a mechanism for different components to guard against the user navigating away from the page when it was not desirable. This used the $window.onbeforeunload event and therefore, only works when navigating outside of the AngularJS application. For in-app navigation, we need to monitor a different event that Angular provides called $locationChangeStart.

$locationChangeStart

In the following code I have expanded saNavigationGuard to include support for $locationChangeStart.

angular.module('somewhatabstract').factory('saNavigationGuard', ['$window', '$rootScope', function($window, $rootScope) {
	var guardians = [];

	var onBeforeUnloadHandler = function($event) {
		var message = getGuardMessage();
		if (message) {
			($event || $window.event).returnValue = message;
			return message;
		} else {
			return undefined;
		}
	};

	var locationChangeStartHandler = function($event) {
		var message = getGuardMessage();
		if (message && !$window.confirm(message))
		{
			if ($event.stopPropagation) $event.stopPropagation();
			if ($event.preventDefault) $event.preventDefault();
			$event.cancelBubble = true;
			$event.returnValue = false;
		}
	};

	var getGuardMessage = function () {
	    var message = undefined;
	    _.any(guardians, function(guardian) { return !!(message = guardian()); });
	    return message;
	};

	var registerGuardian = function(guardianCallback) {
		guardians.unshift(guardianCallback);
		return function() {
			var index = guardians.indexOf(guardianCallback);
			if (index >= 0) {
				guardians.splice(index, 1);
			}
		};
	};

	if ($window.addEventListener) {
		$window.addEventListener('beforeunload', onBeforeUnloadHandler);
	} else {
		$window.onbeforeunload = onBeforeUnloadHandler;
	}

	$rootScope.on('$locationChangeStart', locationChangeStartHandler);

	return {
		registerGuardian: registerGuardian
	};
}]);

In this new version of saNavigationGuard, the getGuardMessage method has been introduced that is responsible for querying the guardians for a reason not to allow navigation. In addition, an event handler has been added on $rootScope to handle $locationChangeStart. This handler is then used to query the guardians and display a confirmation message.

To display the confirmation message, I settled on using $window.confirm. Originally, I had thought about allowing a custom experience instead, but I felt that, due to any alternative experience being non-modal, the state management to allow a navigation to continue would be overly complicated.

Finally…

I was expecting the modifications to support $locationChangeStart to be more difficult than it turned out, though there are certainly some improvements that can be made1.

In the next post, I am going to show how we can track pending web requests and prevent navigation accordingly. In the meantime, please comment and let me know if you have other uses for saNavigationGuard or even alternative implementations.

  1. For example, the old and new URLs that are given as arguments to the $locationChangeStart handler could be passed to the guardians in order for them to make more informed decisions. []

Navigation guard using AngularJS: onbeforeunload

onbeforeunload

I have been working on an add-on for one of our products that includes some data entry components. As part of this, I wanted to make sure that any changes to the data were saved before the user lost interest and went searching the Internet for cat pictures. I quickly turned to the window.onbeforeunload event.

The onbeforeunload  event is the last chance for a website to get the user's attention before they have navigated away to something more shiny or sparkly. In AngularJS, since a real navigation is not going to occur in a single-page application, two events are provided, $locationChangeStart  and $locationChangeSuccess, that can be used to similarly intercept in-app navigations.

Through onbeforeunload and the subsequent browser-based dialog, or the AngularJS events and a subsequent app-based dialog, the user is given the opportunity to cancel the navigation and address something important like unsaved data or a cute cat photo that they almost missed.

So, with events available to intercept navigation, I started hooking them up in all the places that needed them. A directive here, a factory there; before long I was duplicating almost the same code in nearly 20 places. There had to be a better way, so I created the saNavigationGuard service1.

saNavigationGuard

The saNavigationGuard service provides consumers with the ability to register callbacks, known as guardians, that will be called if a navigation event is detected. If a guardian wishes to prevent that navigation, it returns a message explaining why. The saNavigationGuard then signs up to the relevant events and when they occur, asks each guardian if it should go ahead. Whichever guardian returns a string first, wins, and the guardian acts accordingly to prevent the navigation.

In the case of onbeforeunload , the browser continues the event handling by offering the user a choice to continue or cancel the navigation. In the case of the $locationChangeStart  event, this part must be handled by the application. We will come back to how in another post; for right now, let's just look at the onbeforeunload scenario.

Here is the saNavigationGuard factory declaration:

angular.module('somewhatabstract').factory('saNavigationGuard', ['$window', function($window) {
	var guardians = [];

	var onBeforeUnloadHandler = function(event) {
		var message;
		if (_.any(guardians, function(guardian) { return !!(message = guardian()); })) {
			(event || $window.event).returnValue = message;
			return message;
		} else {
			return undefined;
		}
	}

	var registerGuardian = function(guardianCallback) {
		guardians.unshift(guardianCallback);
		return function() {
			var index = guardians.indexOf(guardianCallback);
			if (index >= 0) {
				guardians.splice(index, 1);
			}
		};
	};

	if ($window.addEventListener) {
		$window.addEventListener('beforeunload', onBeforeUnloadHandler);
	} else {
		$window.onbeforeunload = onBeforeUnloadHandler;
	}

	return {
		registerGuardian: registerGuardian
	};
}]);

First thing to note is on line 6 where I have used the any method from underscore (or lodash). This calls a predicate for each element in an array until the predicate returns true. In this case, we are passing our array of guardians and the predicate is calling that guardian to see if it currently wants to stop navigation. If it does, it will return a message.

If one of the guardians returns a message, the message it returns is captured and the predicate returns true. The message is then passed to the event so that the browser will show its dialog. If no guardian returns a message, then the browser is allowed to continue with the navigation unhindered (at least by this code).

Because of how factories are instantiated in Angular, the initialization code that actually signs-up to the onbeforeunload event only occurs once per Angular application. So, injecting this factory into your directives, factories, etc. means the event handling will be initialized just once. This gives a central point to control interception of navigation while allowing individual components to prevent navigation for their own reasons.

Usage

Here is a simple example of how this might be used:

angular.module('somewhatabstract').controller('saEditorThingyCtrl', ['$scope', 'saNavigationGuard', function($scope, saNavigationGuard) {
    var editing = false;
    var navigationGuardian = function() {
        return editing ? "Edit in progress" : undefined;
    };
    
    saNavigationGuard.registerGuardian(navigationGuardian);

    $scope.startEdit = function(){
        if (editing) return;
        editing = true;
        // Stuff happens
    };
    $scope.endEdit = function() {
        if (!editing) return;
        editing = false; 
    };
}]);

Of course, this is a contrived example but it illustrates how easy it is to put the saNavigationGuard to work. In fact, if you didn't want your guardian to be called all the time because you knew it usually would not block navigation, you could only have it registered when needed.

    ...
    var unregisterGuardian;
    
    $scope.startEdit = function(){
        ...
        unregisterGuardian = saNavigationGuard.registerGuardian(navigationGuardian);
        ...
    };
    $scope.endEdit = function() {
        ...
        unregisterGuardian();
        unregisterGuardian = undefined;
        ...
    };
    ...

This ability to register and unregister guardians brings me to my second noteworthy aspect of saNavigationGuard. When registering a new guardian, it is added to the start of the array of guardians rather than the end. This is because, in my use case, the more recently registered guardians are often the most urgent. I suspect this may be common for most uses.

Finally…

This post is the first in a series covering some useful things I have created in my experiences with AngularJS. In the posts to follow, I will be covering how we can expand saNavigationGuard to cover in-app navigation and how we can intercept web requests to provide both navigation guards and busy indication.

I hope you find the saNavigationGuard factory as useful as I have on my current project where I have guardians for active edits and when there are pending POST, PUT or DELETE requests.

If you use this or anything else that I have written about in your project or want to suggest some tweaks or alternatives, please don't forget to leave a comment.

  1. It's really a factory in the AngularJS world, but it's providing a service…oh, I'm not getting into this discussion again, just look up service vs. factory and read about why it doesn't matter as long as you choose. []