javascriptangularjsjasminekarma-jasminehttpbackend

AngularJS + Jasmine: Unexpected http calls


I started writing tests for an existing application and encountered two problems.

Here is service method I'm trying to cover:

    function getClinic(id) {
        return $http
            .get("api/clinic/" + id)
            .then(function (resp) {
                return resp.data;
            })
    }

With

 it('should test getClinic method http call', function() {
  $httpBackend
    .expectGET("api/clinic/" + clinicId)
    .respond(200, $q.when(successResponse));

  clinicManager.getClinic(clinicId)
    .then(function(res) {
      httpOutput = res;
    });

  $httpBackend.flush();

  expect(clinicManager.getClinic).toHaveBeenCalledWith(clinicId);
  expect(httpOutput).toEqual(successResponse);
});

But I got the following error

Error: Unexpected request: GET /api/users/current

Indeed, I do have the following route called on app load

angular
    .module('module', [...])
    .config(...) 
    .run(function (userManager) {
        userManager.setCurrentUser();
        // I put this logic here to fetch currently logged user from back-end on every app load
    })

After removing userManager.setCurrentUser(); I got another error

Error: Unexpected request: GET /dashboard

So the /dashboard is initial page which is specified in $routeProvider

 function Routes($routeProvider) {
    $routeProvider
      .when('/', {
        templateUrl: '/dashboard',
        controller: 'dashboard.ctrl',
      })
      .when('/dashboard', {
        templateUrl: '/dashboard',
        controller: 'dashboard.ctrl',
      })
      //... other routes
     .otherwise({
       redirectTo: '/dashboard',
     });

So my question is how can I avoid getting those two errors without putting http expectations into every single service test kit?


Solution

  • The problem in my case was that I had one module for the whole application and now I understood that this is completely wrong. I split my app into different modules, and when I writing test for specific component there is no need to upload the whole application, only module the component belongs to. I removed application .run and routeProvider configurations into independent module therefore no need to upload the new config module when I'm testing nested components.