$httpBackend.expectGET fails if controller makes request on page load

83 views Asked by At

I've just killed hours of my live trying to solve this. In a controller I call a method making an HTTP request on page load:

$scope.getPosts = function() { /* call to service */ };
/// Call it immediately
$scope.getPosts();

I expect this in my unit test:

$httpBackend.expectGET("/posts?bar=bar&foo=foo").respond(200, []);

But Karma reports

Error: Unexpected request: GET /posts?bar=bar&foo=foo
No more request expected in ...

That doesn't make any sense. I tried all combinations of when/where to call expectGET/create the controller in my tests but nothing helped. Then I realized I have another controller that fetches some data on page load and working tests for it. The difference is, a route parameter must be present for the HTTP request to happen. So I moved the call to

if ($routeParams.foo) {
  $scope.getPosts();
}

and injected the foo param in the test. It passed! Obviously no-one wants the visitors to see such a thing in the URL. Using whenGET instead also makes it pass.

Can someone please help with solving this issue? I found one guy asking about this almost 2 years ago but he didn't get any answer (except mine which was deleted).

0

There are 0 answers