If you’ve seen any of my Angular code, you will notice that I use a LOT of element directives (Angular 2 calls these “components”!). You’ll also notice that I like writing a lot of unit tests.
After my previous post on WebStorm templates, I came to the realization that I was writing a lot of boiler plate code for testing these directives. Instead of rewriting these tests every time, I’ve created a template to use for unit testing directives.
(One thing to note, this requires at least angular mocks 1.3.15 for the bindings options in the $controller
constructor)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
describe('My Great Directive', function() { | |
var $rootScope; | |
var $controller; | |
var $window; | |
var $httpBackend; | |
var $compile; | |
var scope; | |
var MyFancyService | |
var MyGreatDirectiveController; | |
beforeEach(function() { | |
module('myApp.greatDirective'); | |
inject(function(_$rootScope_, _$httpBackend_, _$compile_, _$controller_, _$window_, _MyFancyService_) { | |
// Native Angular Injections | |
$rootScope = _$rootScope_; | |
$controller = _$controller_; | |
$window = _$window_; | |
$compile = _$compile_; | |
$httpBackend = _$httpBackend_; | |
scope = $rootScope.$new(); | |
// Custom Injections | |
MyFancyService = _MyFancyService_; | |
// Locals are the injections to the directive's controller | |
var locals = { | |
$window: $window, | |
MyFancyService: MyFancyService | |
}; | |
// Bindings are the objects that are bound to the directive's scope | |
var bindings = { | |
fancyString: 'fancy-string' | |
}; | |
MyGreatDirectiveController = $controller( | |
'MyGreatDirectiveController', | |
locals, | |
bindings | |
); | |
}); | |
}); | |
describe('Directive Controller', function() { | |
it('should be a proper contoller', function() { | |
expect(MyGreatDirectiveController).toBeDefined(); | |
}); | |
}); | |
describe('Compiled Directive', function() { | |
var responseText; | |
beforeEach(function() { | |
responseText = 'My Great Directive!'; | |
$httpBackend.whenGET('/app/partials/great.directive.html').respond(responseText); | |
}); | |
it('should compile', function() { | |
var element = $compile('<my-great-directive></my-great-directive>')(scope); | |
scope.$digest(); | |
$httpBackend.flush(); | |
expect(element.html()).toContain(responseText); | |
}); | |
}); | |
}); |