0

I have a factory called myFactory that has as dependency $http. In my tests I want to mock this dependency. I found out that I could achieve it using $httpBackend. I did using the code below and it works. But I don't understand why. At what moment angular knows that httpBackend is in fact replacing the $http that is inside myFactory ?

beforeEach(inject(function(_myFactory_, _$httpBackend_){
    myFactory = _myFactory_;
    $httpBackend = _$httpBackend_;
}));

1 Answer 1

7

It's not replacing $http, its replacing a service called $httpBackend that you've never used because its only used internally. Angular has lots of 'private' services that it uses. So $http is injected with the real $httpBackend normally but when angular-mocks.js is loaded up (after angular.js, order is important) it basically overwrite the real $httpBackend with the mock one.

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

6 Comments

Thank you !!! So, once angular-mocks.js is loaded, what else does get automatically mocked? I didn't find any doc telling it.
All these things: docs.angularjs.org/api/ngMock#object. $timeout has a handy .flush() method added to it that can flush all pending timeouts. You mush flush timeouts that have been queued up. Plus more stuff...
Let me see if I understand, once angular-mocks is loaded (by calling inject inside beforeEach), automatically mocks are created for $exceptionHandler, $log, $interval, $httpBackend and $timeout. Any other object I ask angular to provide me, will be a real implementation. Is that correct?
Yes all other objects are the real objects (you'd have to mock those out as well if you didn't want the real one). Also mocks isn't loaded by the call to inject, its loaded when its loaded via <script src='angular-mocks.js'> or in the case of karma when its added to the files array in the karma.conf.js file.
@nfiniteloop how angular replaces a service? I am trying to find this in angular code but can not. Where does it do in angular code?
|

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.