Mocking my own service in a unit test

angularjs, mocking, unit-testing

Solution

Here is an example from my open source project: https://github.com/lucassus/mongo_browser/blob/f1faf1b89a9fc33ef4bc4eced386c30bda029efa/spec/javascripts/app/services_spec.js.coffee#L25 (sorry for coffeescript). Generally inside a spec you have to create and include a new module which overrides the given service.

Problem

I have a service that takes several of my other services as a dependency. How can I mock it out for a unit test? ``` myApp.factory('serviceToTest', ['serviceDependency', function(serviceDependency) { return function(args) { return cond(args) ? serviceDependency() : somethingElse(); }; } ]); ``` In the above example, I want to mock out `serviceDependency` so I can verify that it was called. How can I do that? I could just do the following in the test: ``` describe("Services", function() { describe('serviceToTest', function() { myApp.factory('serviceDependency', function() { var timesCalled = 0; return function() { return timesCalled++; } }); it('should do foo', inject(function(serviceToTest, serviceDependency) { serviceToTest(["foo", "bar", "baz"]); expect(serviceDependency()).to.equal(1); }); }); }); ``` This works fine for the test that needs the mock, but it then affects the state of all the other tests that follow, which is obviously a problem.

Original source