I'm trying to test my AngularJs services using Jasmine but I keep getting all kinds of errors. So I tried to create a very basic Sum service to test it and the errors keep on coming.
This is the AngularJS service I'm trying to test:
angular.module('base', [])
.service('operacoes', [function () {
this.somar = function (n1,n2) {
return n1 + n2;
};
}]);
And my test:
/// <reference path="../../Scripts/angularjs/angular.min.js" />
/// <reference path="../../Scripts/angularjs/angular-mocks.js" />
/// <reference path="../../ServicoBase.js" />
describe("Testing Services", function () {
var operacoesObj;
beforeEach(angular.module('base'));
beforeEach(inject(function (operacoes) {
operacoesObj = operacoes;
}));
it('deve ter inicializado', function () {
expect(operacoesObj).toBeDefined();
});
it('deve conseguir somar 2 números', function () {
expect(operacoesObj.somar(5, 1)).to.equal(6);
});
});
Trying to run this tests returns me the following errors:
I've tried other Jasmine versions like 2.4.1 (running now on 2.5.2).
Testing services is not the same as testing controllers. You should use $injector.get()
to return an instance of a service. I changed your test code to the following and the tests are passing:
describe("Testing Services", function () {
var svc;
beforeEach(function() {
angular.mock.module('base')
inject(function($injector) {
svc = $injector.get('operacoes');
})
});
it('deve ter inicializado', function () {
expect(svc).toBeDefined();
});
it('deve conseguir somar 2 números', function () {
expect(svc.somar(5, 1)).toEqual(6);
});
});
See the angular documentation for unit testing services here.
In addition, having a test to check if a service is defined is not really necessary. You will know if the service is not defined because all of your other unit tests will fail if it isn't.