Freewind
Freewind

Reputation: 198188

How to mock a service and inject it to another service?

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?

Upvotes: 0

Views: 262

Answers (1)

David Bohunek
David Bohunek

Reputation: 3201

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;
});

Upvotes: 1

Related Questions