samyak bhalerao samyak bhalerao - 4 months ago 18
AngularJS Question

How to test functions inside angularjs services using jasmine-karma

I am new to karma-jasmine testing.I have written one service which makes http get call to api and returns data object.

app.service('service_name',['$http',function($http){
this.getData=function(urlPath){
var Data = $http.get(path).success(function(data){
var getData = data;
console.log("getData success");
return getData;
}).error(function(response){
var getData = response;
console.log("getData error");
return getData;
});

console.log(Data);
return Data;
};
}]);


From controller I am passing url to this service function and getting data using
.then()
callback;

service_name.getData(url).then(function(data){
console.log('expected data: ', data);
});

Answer

Here is how I did it:

First, setup the test environment according to this article

Then in the test spec, use the following test template to test your functions in service, thanks Ben Lesh for his great blog

'use strict';

describe('service_name', function() {
  var service_name,
    httpBackend,
    resource;

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

    // The injector ignores leading and trailing underscores here (i.e. _$httpBackend_).
    // This allows us to inject a service but then attach it to a variable
    // with the same name as the service in order to avoid a name conflict.
    inject(function($injector, _service_name_) {
      service_name = _service_name_;
      httpBackend = $injector.get('$httpBackend');
    });
  });

  // make sure no expectations were missed in your tests.
  // (e.g. expectGET or expectPOST)
  afterEach(function() {
    httpBackend.verifyNoOutstandingExpectation();
    httpBackend.verifyNoOutstandingRequest();
  });

  it('should have a getData function', function() {
    expect(angular.isFunction(service_name.getData)).toBe(true);
  });

  it('getData function should return data object if http request is successful', function() {
    var expectedData = data;
    httpBackend.expectGET('urlPath')
      .respond(expectedData);

    var actualResult;
    service_name.getData().then(function(response) {
      actualResult = response;
    });

    httpBackend.flush();

    expect(actualResult).toEqual(expectedData);
  });

  it('getData should return error message when http request is unsuccessful', function() {
    httpBackend.expectGET('urlPath').respond(500);

    var promise = service_name.getData('urlPath'),
      result = null;

    promise.then(function(foo) {
      result = foo;
    }, function(reason) {
      result = reason;
    });
    httpBackend.flush();
    expect(result).toBe("getData error");
  });

});

Hope this helps.

Comments