lundi 25 avril 2016

Inject constant to service and test promise

I have a simple service that queries an api to fetch some data using promises for the controllers. I want to test services alone using jasmine. However, the services are dependent on some constants that I inject to get the api urls.

Here is how the service is defined:

angular.module('dbRequest', [])
  .factory('Request', ['$http', 'localConfig', function($http, localConfig){
    return {
      getRevision: function(){
          return $http({
            url: localConfig.data,
            method: "GET",
            crossDomain: true,
            headers: {
              'Content-Type': 'application/json; charset=utf-8'
            }
          })
      }
}]);

localConfig is defined as constants in app.js. Following this tutorial, here is how I am testing the service:

describe('Service: Request', function () {

  // load the controller's module
  beforeEach(module('webApp'));

  var reqService, $q, $scope, lc;

  beforeEach(function(){
    inject(function($injector){
      reqService = $injector.get('Request');
      $q = $injector.get('$q');
      lc = $injector.get('localConfig');
      $scope = $injector.get('$rootScope').$new();
    });
  });

  it('should test service definition', function(done){
    expect(reqService).toBeDefined();
    done();
  });

  it('should get db revision', function(done){
    spyOn(reqService, ['getRevision']).and.returnValue($q.when({/*what comes here??*/}));
    reqService.getRevision().then(function(res){
      expect(res.length).toBe(1);
      done();
    });
    $scope.$digest();
  });
});

I need to test whether the length of the data returned from the api (which is an array) is greater than 0. Which determines if the test passes in this case. This poses 2 problems here:

  • How to inject constants in the service?
  • How to test the response?

My response looks like this:

data: ["option1", "option2"]

Aucun commentaire:

Enregistrer un commentaire