14

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)

2 Answers 2

25

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I looked at this about 5 times before I realized that the response also needs to be declared on the expectGET. I was under the impression that the whenGET was the only place where it was necessary to declare the response. Is is safe to say that one must declare a response on both the whenGET and expectGET?
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.