Angular unit tests - module and inject
Demonstrating usage of module and inject from angular mocks
HTML
<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.0.5/angular.js"></script>
<script src="http://code.angularjs.org/1.0.5/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
angular.module('myApp', []).service('MyService', ['ConfigService', function (configService) {
this.foo = function () {
return configService.get('foo');
};
this.bar = function () {
return configService.get('bar').toString() + 'baz';
};
}]);
// --- SPECS -------------------------
describe('myApp', function () {
var configServiceSpy, myService;
beforeEach(function () {
configServiceSpy = jasmine.createSpyObj('ConfigService', ['get']);
// Provide mock implementation of configService
module(function ($provide) {
$provide.value('ConfigService', configServiceSpy);
});
// Register module configuation code for myApp
module('myApp');
// Inject service under test
inject(function (MyService) {
myService = MyService;
});
var windowObj = {location: {href: ''}};
beforeEach(mock.module(function($provide) {
$provide.value('$window', windowObj);
}));
// Try to register additional module configuation code
/*
module(function ($provide) {
$provide.value('ConfigService', configServiceSpy);
});
*/
});
it('tests the window', function(){
expect(windowObj.location.href).toEqual('/secure/regulations/1/attachment');
});
xit('uses the mock service', function () {
myService.foo();
expect(configServiceSpy.get).toHaveBeenCalled();
configServiceSpy.get.andReturn('spy');
expect(myService.bar()).toEqual('spybaz');
});
xit('injects other services', inject(['$exceptionHandler', function ($exceptionHandler) {
myService.foo();
expect(configServiceSpy.get).toHaveBeenCalled();
expect($exceptionHandler.errors).toBeUndefined();
}]));
});
// --- Runner -------------------------
(function () {
var jasmineEnv = jasmine.getEnv();
jasmineEnv.updateInterval = 1000;
...