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.
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');
});
});