Angular unit tests - module and inject
Demonstrating usage of module and inject from angular mocks
by eitanp461
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;
});
// Try to register additional module configuation code
/*
module(function ($provide) {
$provide.value('ConfigService', configServiceSpy);
});
*/
});
it('uses the mock service', function () {
myService.foo();
expect(configServiceSpy.get).toHaveBeenCalled();
configServiceSpy.get.andReturn('spy');
expect(myService.bar()).toEqual('spybaz');
});
it('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;
var htmlReporter = new jasmine.HtmlReporter();
jasmineEnv.addReporter(htmlReporter);
jasmineEnv.specFilter = function (spec) {
return htmlReporter.specFilter(spec);
};
var currentWindowOnload = window.onload;
window.onload = function () {
...