marcel
marcel

Reputation: 3272

AngularJS Jasmine testing get-request

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)

Upvotes: 14

Views: 8259

Answers (2)

iberbeu
iberbeu

Reputation: 16235

Just in case it helps and because it happened to me, although it is not the exact case of the question. I had these two lines:

$httpBackend.whenGET(myService.serviceURL).respond(myMock);
$httpBackend.expectGET(myService.serviceURL);

With when I wanted to define what to response when calling the service and with expect I wanted to check that the method was called.

This doesn't work (although sometimes it does, I don't know why). I guess somehow expect is overriding when and therefore I got

Error: No response defined !

The solution was to remove the when clause and add respond() to expect

$httpBackend.expectGET(myService.serviceURL).respond(myMock);

I don't know why the framework behaves that way. If someone knows it would be nice that you explain it here to improve the answer

Upvotes: 1

Pascal Le Merrer
Pascal Le Merrer

Reputation: 5981

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.

Upvotes: 25

Related Questions