Question

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)
Était-ce utile?

La solution

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.

Autres conseils

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

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top