How to unit test AngularJS Decorators
You could use decorators to enhance any kind of AngularJS module. Unit testing a decorator is all about testing the kind of service that you’re dealing with and making sure that the expected behaviour is what actually happens. So, if you’re decorating a service you’ll write tests for services, if you’re decorating directives you’ll write tests for directives (make sense, huh?).
Get Ciro Nunes’s stories in your inbox
Join Medium for free to get updates from this writer.
In this article we will see how to decorate an Angular core directive and unit test it.
Decorating a native Angular directive
Let’s suppose that we want to augment the $rootScope service to log the number of times that the $apply method were called.
angular.module('cn.rootScope', [])
.config(function($provide) {
// create a decorator
$provide.decorator('$rootScope', function($delegate) {
// in this case $delegate == $rootScope
// otherwise $delegate would be an array of
// directives registered as the decorator name
var times = 1; // augument the apply method to log how many times
// it was called
$delegate.$apply = loggerify($delegate.$apply); function loggerify(fn) {
return function() {
fn.apply(this, arguments);
console.log(times);
times += 1;
}
} return $delegate;
});
});
Setting up the test environment
First of all we need that our test run after load angular.js and angular-mocks.js. Here is an example considering that we are using Karma and Bower.
module.exports = function(config) {
config.set({
basePath: ‘’,
frameworks: [‘jasmine’],
files: [
‘bower_components/angular/angular.js’,
‘bower_components/angular-mocks/angular-mocks.js’,
‘src/*.js’,
‘test/*.js’
],
browsers: [‘Chrome’],
});
};Bootstraping the test suite
Now that we have all set, let’s bootstrap our test file.
describe(‘Decorator: $rootScope’, function() {
// load the angular.module using angular-mocks
beforeEach(module(‘cn.rootScope’)); var $rootScope; // before each spec runs
beforeEach(inject(function(_$rootScope_) {
$rootScope = _$rootScope_;
})); // the specs will be here
});
Creating our specs
In case of our decorator we’ll need only one spec. All we need to do is make sure that for each time that we call the $apply method, console.log is called with the next value.
it('should log how many times the $apply
method was called', function() {
spyOn(console, 'log');
$rootScope.$apply();
$rootScope.$apply();
$rootScope.$apply();
expect(console.log).toHaveBeenCalledWith(1);
expect(console.log).toHaveBeenCalledWith(2);
expect(console.log).toHaveBeenCalledWith(3);
});This pattern could be used to test pretty much any kind of decorator that augment core services. Have fun!








