AngularJS Jasmine testing get-request

marcel picture marcel · Mar 13, 2014 · Viewed 8.1k times · Source

I have a factory to execute a get request, I'd like to test. Unfortunately the karma test tells me that there is not response defined at $httpBackend.

AngularJs 1.2.14, Jasmine 2.0, Karma 0.12.0

Here's my module I'd like to test:

var appFactory = angular.module('appFactory', []);

appFactory.factory('boxListService', function($http){
    return{
        getList: function(){
            return $http.get('/boxlist').then(function(result){
                return result.data;
            });
        }
    };
});

My test is this:

describe('Module-Test', function() {

    beforeEach(module('appFactory'));

     it('should call $http.get in getList', inject(function (boxListService, $httpBackend){
        $httpBackend.expectGET('/boxlist');
        boxListService.getList();
        $httpBackend.flush();
      }));
});

Message:

Error: No response defined !
at $httpBackend (D:/nodeJS/host/test_app/src/public/js/libs/angular/angular-mock.js:1206:13)

Answer

Pascal Le Merrer picture Pascal Le Merrer · Mar 13, 2014

You have to define the expected response, as well as the expected request. It will have the form:

$httpBackend.expectGET('/boxlist').respond(HTTP_STATUS_CODE, EXPECTED_RESPONSE);

HTTP_STATUS_CODE is an integer. EXPECTED_RESPONSE is the value to be returned (it's often an Object Literal).

You may define only one of them.

Look at ngMock httpBackend documentation for more information.