1

I'm trying to test a controller with a custom service dependency. The service has a dependency on $http. In my controller, I'm making reference to the "then" part of the promise, but that is making the test code blow up. How are you supposed to mock a service and test a controller dependent on it? Here's a plunker with the whole debacle. My service looks like this:

  app.service('FooService', ['$http', function($http){
    return {
      getFoo: function(){
        return $http.get('Foo');
      },
      getBar: function(){
        return 'bar';
      }
    };
  }]);

The controller:

  app.controller('FooController', ['$scope', 'FooService', function(scope, FooService){
    scope.hi = function() {};

    scope.getFoo = function(){
      FooService.getFoo().then(function(data){
        scope.bar = data.data;
      });
    };

    scope.getBar = function(){
      scope.bar = FooService.getBar();
    };
  }]);

In my understanding, the $http dependency should not be on the controller in order to drive testability and separation of concerns. However, now I'm having trouble with the promise... How should this be done properly?

1 Answer 1

1

You can use $httpBackend to mock out the http call. In your plunker the main reason httpBackend wasn't working is because you were calling respond(1) which responded with an HTTP status code of 1. If you change it to respond(200, 1) then it should work:

http://plnkr.co/edit/ubJH3iABaGpINFKTvGTx?p=preview

You can also just mock out the FooService using angular's $q service to create a promise similar to the one $http returns. You'll also need to call scope.$apply() to let the promise resolve similar to how you call $httpBackend.flush() in the other example. Here is a working sample:

http://plnkr.co/edit/3xbCmBTQ4ChVlhaTZXwC?p=preview

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! IMO testing in Angular isn't as easy as advertised - lots of ways to screw things up.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.