mercredi 23 septembre 2015

Testing factories (services) in AngularJS

I have tried several combinations to test my factory but always get errors in the view SpecRunner.html.

So let's have a look at my factories and the tried unit tests.

//First service who communicated with the REST API
angular.module('testApp')
    .factory('ResService', ['$resource', 'baseUrl',
        function ($resource, baseUrl) {
            return {
                group: $resource(baseUrl + '/api/qr_group/:Id', {
                    Id: '@Id'
                }, {})
...

//Second service who uses ResService and who will used in the controller
angular.module('testApp')
    .factory('CrudService', ['ResService',
        function (ResService) {
            var service = {
                getAllGroups: getAllGroups,
            };

            return service;

            function getAllGroups() {
                return ResService.group.query();
            }
}]);

Well, my target is to check whether the service called an object or a status 200. I've decided to returning an object for myself.

Here the wrong code:

describe('Services: CrudService', function () {

  var CrudService,
      $httpBackend,
      mockData;

  beforeEach(module('testApp'));

  beforeEach(inject(function ($injector) {
        $httpBackend = $injector.get('$httpBackend');
        CrudService = $injector.get('CrudService');
        mockData = {
            Id: 1,
            name: 'USA',
            code: 'US'
        };

        $httpBackend.expectGET('http://localhost:63831/api/group').respond([
            {
                Id: 1,
                name: 'USA',
                code: 'US'
            }
        ]);
  }));

  afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
  });

  it('do it', function () {
        var result = CrudService.getAllGroups();

        $httpBackend.flush();

        expect(result[0]).toEqual(mockData);
  });

The following errors I've received:

Error: [$rootScope:inprog] http://ift.tt/1KuyNME$rootScope/inprog?p0=%24digest in http://localhost:60694/js/angular.min.js (line 6)

and

Error: Unexpected request: GET views/groups.html No more request expected in http://localhost:60694/js/angular-mocks.js (line 1244)

I don't know what the problem is.. can anyone help me?

Aucun commentaire:

Enregistrer un commentaire