vendredi 25 septembre 2015

Testing a simple REST service with Jasmine (AngularJS)

After trying many samples I'm coming to end. I don't know what to do that the test is working..

I've tried the following to test:

//CrudService who is invoked in the Ctrl
angular.module('myApp')
    .factory('CrudService', ['ResService',
        function (ResService) {
            var service = {
                getAllCompanies: getAllCompanies
            };

            return service;

            function getAllCompanies() {
                return ResService.company.query();
            }
...

//That's the nested service ResService

angular
    .module('myApp')
    .factory('ResService', ['$resource', 'baseUrl',
        function ($resource, baseUrl) {
            return {

                company: $resource(baseUrl + '/api/company/:Id/:code', {
                    Id: '@Id',
                    code: '@code'
                }, {
                    'update': {
                        method: 'PUT'
                    }
                }),
...

Now, I want to test CrudService.getAllCompanies() whether it returned something.

The following code was an attempt:

describe('CrudService', function () {
  var httpBackend, mockCrudService, baseUrl;
  var mockData = {
     Id: 1,
     cname: 'Company World Inc.',
     shortcode: 'ABCD',
     maxValue: 3,
     GroupId: 1
  };

  beforeEach(function () {
     module('myApp');

     inject(function ($injector) {
       httpBackend = $injector.get('$httpBackend');
       mockCrudService = $injector.get('CrudService');
       baseUrl = $injector.get('baseUrl');
     });
  });

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

  it('test the service', inject(function (CrudService) {
       httpBackend.expectGET(baseUrl + '/api/company').respond(200, mockData);

       var result = mockCrudService.getAllCompanies(mockData);

       httpBackend.flush();

       expect(result.shortcode).toEqual(mockData.shortcode);
  }));

It doesn't work. I'm always getting the following Error messages:

Error: Unexpected request: GET views/fonds.html
No more request

and

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

Aucun commentaire:

Enregistrer un commentaire