0

I have a service that calls a REST URL that returns data.

My sample code would be

$http('POST', '/mockUrl/resource/'+resourceValue).then(...);

My service works fine and it returns data. My problem is how do I test this in karma. Right now I have a different resourceValue to be tested for the mockUrl being called. Before coming to stackoverflow, in each test i was defining $httpBackend with the expected URL.

eg:

it('testing for status 200', function(){
        $httpBackend.when('POST', '/mockUrl/resource/'+1234)
           .respond(function (method, url, data, headers) {
               return [200, data1];
           });

       MyService.serviceMethod(1234).then(function(){
      //test the returned data
      });
   });

it('testing for status 201', function(){
    $httpBackend.when('POST', '/mockUrl/resource/'+4567)
        .respond(function (method, url, data, headers) {
           return [201, data2];
          });

    MyService.serviceMethod(1234).then(function(){
       //test the returned data
    });
 });

I am being told that I should not be writing my karma tests in the above manner. But I am not sure how to avoid that.

I have tried

$httpBackend.when('POST',url)
      .respond(function (method, url, data, headers) {
        return data[option];
      });

But this 'url' never gets called in any test. I am not sure how to proceed further.

manu
  • 77
  • 1
  • 3
  • 14

1 Answers1

0

it seems that you never call $httpBackend.flush(); that is needed to simulate async operations... Plus, you also never use

afterEach(() => {
  $httpBackend.verifyNoOutstandingExpectation();
  $httpBackend.verifyNoOutstandingRequest();
});  

Probably you need to have a more in-deep view at https://docs.angularjs.org/api/ngMock/service/$httpBackend

Hitmands
  • 13,491
  • 4
  • 34
  • 69
  • actually I call $httpBackend.flush() and check for $httpBackend.verifyNoOutstandingExpectation(); $httpBackend.verifyNoOutstandingRequest(); after every call. my issue is that I need to return different response for a different status( I have 4 such statuses). is it possible to have just 1 httpBackend calling different urls and still fulfilling my use case. – manu Sep 14 '16 at 12:34