Testing angular providers with Jasmine
Testing angular providers with Jasmine
by igor_nov
HTML
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.js"></script>
<script src="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine-html.js"></script>
<link rel="stylesheet" href="http://pivotal.github.io/jasmine/lib/jasmine-1.3.1/jasmine.css">
<script src="http://code.angularjs.org/1.0.5/angular.js"></script>
<script src="http://code.angularjs.org/1.1.4/angular-mocks.js"></script>
JavaScript
//--- CODE --------------------------
var myApp = angular.module('myApp', []);
// Create a map-based configuration service
myApp.provider('MyService', function () {
var service = {};
service.configureSomething = function () {
return 461;
};
service.$get = function () {
return {};
};
return service;
});
// --- SPECS -------------------------
describe('myApp', function () {
var myServiceProvider;
beforeEach(function () {
// Initialize the service provider by injecting it to a fake module's config block
angular.module('testApp', function () {})
.config(function (MyServiceProvider) {
myServiceProvider = MyServiceProvider;
});
// Initialize myApp injector
module('myApp', 'testApp');
// Kickstart the injectors previously registered with calls to angular.mock.module
inject(function () {});
});
it('tests the providers internal function', function () {
expect(myServiceProvider.configureSomething()).toEqual(461);
});
});
// --- 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 () {
if (currentWindowOnload) {
currentWindowOnload();
}
execJasmine();
};
function execJasmine() {
jasmineEnv.execute();
}
})();