sms
sms

Reputation: 426

Unit Testing $http using Jasmine

I am supposed to mock an ajax call using jasmine.

Following is my code snippet.

var httpBackend;
var http;

beforeEach(inject(function ($injector) {
    $httpBackend = $injector.get('$httpBackend');
    scope = $injector.get('$rootScope').$new();
    var $controller = $injector.get('$controller');
    var MainCtrl = $controller('scanningClientsController',
        { $scope: scope });
}));

   it("Verify Ajax Call", function () {    
    var test;
    $httpBackend.expectGET(scope.requestUrl).respond([{}, {}, {}]);      
    scope.GetClients().then(function (response) {
        test = response;
    });
    $httpBackend.flush(); 
    expect(test.length).toBe(3);

My function in controller is as follows:

  $scope.GetClients =
         function () {
             $http({
                 method: 'GET',
                 url: $scope.requestUrl,
             }).success(function (response, status, headers, config) {
                 $scope.scanningClientsList = response.data;

             }).error(function (data, status, headers, config) {

             });
         };

Now I get an error

TypeError: 'undefined' is not an object (evaluating 'scope.GetClients().then')

Tried fix from this http://chutzpah.codeplex.com/workitem/230

But it doesnt seem to fix the issue. Any ideas?

Upvotes: 1

Views: 272

Answers (1)

domakas
domakas

Reputation: 1246

You need to inject $httpBackend also:

$httpBackend = $injector.get('$httpBackend');

Edit

You are not returning promise in your $scope.GetClients function, so you actually are calling then to undefined..

Try something like this:

 $scope.GetClients =
     function () {
         var deferred = $q.defer();
         $http({
             method: 'GET',
             url: $scope.requestUrl,
         }).success(function (response, status, headers, config) {
             $scope.scanningClientsList = response.data;
             deferred.resolve(response.data);

         }).error(function (data, status, headers, config) {
             deferred.reject(data);
         });
         return deferred.promise;
     };

Upvotes: 1

Related Questions