0

I have a service which is being tested:

angular.module('services', []).
  service('myService', function(topService) {});

And the topService is another angularjs service.

Now I want to write unit test for myService, but I need to mock the topService and pass it to myService.

I tried but not sure how to make it work:

define(['angular', 'angularMocks', 'services/my'], function(_, mocks, _) {

    beforeEach(mocks.module('services'));

    describe("my service", function() {

        it("should do something", mocks.inject(function(myService) {
            // how to mock and inject a `topService` to `myService` ????
            expect(myService).doSomething().toEqual("???");
        }));
    });
});

How to do that?

mehdi lotfi
  • 11,194
  • 18
  • 82
  • 128
Freewind
  • 193,756
  • 157
  • 432
  • 708

1 Answers1

1

First create the mockedTopService, provide any function which will be needed by the test to run:

var mockedtopService = {
    doSomething: function() {
        return "test";
    }
};

Then provide it to angular using $provide:

beforeEach(function () {
    module(function ($provide) {
        $provide.value('topService', mockedtopService );
    });
}

In case you need to get an instance of the service via angular you can do it this way:

inject(function (topService) {
    var topServiceInstance = topService;
});
David Bohunek
  • 3,181
  • 1
  • 21
  • 26
  • in the module, shouldn't you return null so it doesn't mess up previously injected module? – maurycy Aug 05 '14 at 08:21
  • 1
    How would it mess it up? Can you explain me more what you mean with your question, please? – David Bohunek Aug 05 '14 at 08:29
  • Thank you. I tried similar solution, but I found the `topService` I mocked here, will make the tests in other files fail. Very strange. – Freewind Aug 05 '14 at 08:41
  • Sorry for being unclear, It happened to me that when I had module like the one in your answer after using `module('myWebApp')` it caused weird behaviour in tests, and when I did `return null` it get stable again. I mean your answer is correct for sure, I was just wondering if this behaviour is common or it was like that just for me – maurycy Aug 05 '14 at 08:42
  • 1
    @Freewind then the tests are not good, they should be stateless and clearly from what you are saying they inherit from previous tests – maurycy Aug 05 '14 at 08:43
  • @maurycy I see. It has never happened to me so I can't tell. Would be nice to see full code. – David Bohunek Aug 05 '14 at 08:46
  • I found that I should put the `beforeEach(module(...))` inside the `describe(...)`. If I put them outside, it will impact other tests – Freewind Aug 05 '14 at 08:56