3

In my module.run block it is calling a method on a service I have made. When running my tests I want it to reference a mock service instead of the real one which is making http requests. I am currently trying to test a controller, not the actual run block itself - how can I inject the mock service into the run function? I have tried using $provide.factory but it doesn't seem to do anything and is still loading the service as normal.

I am using Jasmine to write my tests.

app.js

angular.module("app")
    .run(function(MyService) {
        MyService.log("starting app");
    });

test.js

describe("MyController", function() {

    beforeEach(function() {
        module(function ($provide) {
            $provide.factory("MyService", { log: function(){} });
        });
    });

    // I want module 'app' to execute its run function using injected value for MyService
    beforeEach(module("app"));

    beforeEach(inject(function($controller, $rootScope) {
        MyController = $controller("MyController", { $scope: $rootScope.$new() });
    }));

    ...........

});
2
  • 2
    Is testing the module's run block essential to your unit test? Angular's recommendation is to declare the run block in an isolated module so it can easily be ignored in unit tests, see docs.angularjs.org/guide/module#run-blocks Commented Sep 7, 2015 at 9:35
  • I don't want to test the run block, but it is executing automatically when I load the module in my tests, and then calling this service which I don't want it to do Commented Sep 7, 2015 at 21:51

1 Answer 1

5

In this case is important order.

You need load your app first

beforeEach(module("app"));

and then overwrite MyService definition.

beforeEach(
  module({
    "MyService": {
      log: function(message) {
        console.log("MyFakeService called: " + message);
      }
    }
  })
);

Otherwise app service implementation is last registred and used.

working example is here - look to the console http://plnkr.co/edit/BYQpbY?p=preview

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

1 Comment

I'm doing the same like this but still didn't get fakeService. is there any other way to do the same?

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.