0
votes

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:

  • TypeError: Object doesn't support property or method 'call'
  • [$injector:unpr] http://errors.angularjs.org/1.4.4/$injector/unpr?p0=operacoesProvider%20%3C-%20operacoes
  • Expected undefined to be defined.

I've tried other Jasmine versions like 2.4.1 (running now on 2.5.2).

2

2 Answers

3
votes

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.

0
votes

Try this:

describe("Testing Services", function() {
  beforeEach(module('base'));

  it('deve ter inicializado', inject(function(operacoes) {
    expect(operacoes).toBeDefined();
  }));


  it('deve conseguir somar 2 números', inject(function(operacoes) {

    expect(operacoes.somar(5, 1)).toEqual(6);

  }))

});