3

I'd like to test that a (component's) controller is sending a GET request to some URL (without caring about the response). I was expecting that

httpBackend.expectGET('/some/random/url');

would spy on the http backend and fail if it did not get the GET request, so I was expecting the following spec to fail:

describe('myApp', function() {
  var httpBackend;

  beforeEach(module('myApp'));

  beforeEach(inject(function($httpBackend) {
    httpBackend = $httpBackend;
  }));

  it('sends a GET request to /some/random/url', function() {
    httpBackend.expectGET('/some/random/url');
    httpBackend.expect('GET', '/some/random/url');
  });

});

But this seems to pass trivially

Starting the Teaspoon server...
Teaspoon running default suite at http://127.0.0.1:56255/teaspoon/default
..

Finished in 0.01200 seconds
2 examples, 0 failures

with this:

angular.module('myApp', []);

So I suppose I am misunderstanding what expectGET is doing and this is not the way the way to check what I am trying to check.

sunless
  • 597
  • 5
  • 19

2 Answers2

2

I usually add the following code to any spec (test) files deal with http mocking. This makes sure that the call is flushed and that there are no outstanding expectations / requests.

afterEach(() => {
    try {
        $httpBackend.flush();
    } catch (e) {
    } 
    $httpBackend.verifyNoOutstandingExpectation();
    $httpBackend.verifyNoOutstandingRequest();
});

This would change your code like so

describe('myApp', function() {
  var httpBackend;

  beforeEach(module('myApp'));

  beforeEach(inject(function($httpBackend) {
    httpBackend = $httpBackend;
  }));

  afterEach(() => {
      try {
          httpBackend.flush();
      } catch (e) { // entering here is a sign your unit test failed
      } 
      httpBackend.verifyNoOutstandingExpectation();
      httpBackend.verifyNoOutstandingRequest();
  });

  it('sends a GET request to /some/random/url', function() {
    httpBackend.expectGET('/some/random/url');
    httpBackend.expect('GET', '/some/random/url');
  });

});
Igor
  • 60,821
  • 10
  • 100
  • 175
  • Thanks. `httpBackend.verifyNoOutstandingExpectation();` gives the error I was waiting for. (So you have to flush after each spec explicitly otherwise requested will stick between specs?) – sunless Apr 05 '16 at 19:29
  • @sunless - With the `afterEach` it should flush after completion of each `it`. I guess it also depends on how you have your tests structured, with many calls or nested `it` specs you might have to change it up. I prefer one call / test per `it` block so the afterEach works for me in that way. – Igor Apr 05 '16 at 19:31
0

You forgot to call flush() on httpBackend. That's when it will check that all the expected requests have been received.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255