I'm creating unit tests for my AngularJS application's controllers. In myapp.run I'm injecting and using a factory, called UsersFactory, somehow like this:
myApp.run(['$rootScope','UsersFactory', function ($rootScope,UsersFactory) {
UsersFactory.getMe().then(function(data)
{
//..
});
}]);
I created a Mock for UsersFactory called UsersFactoryMock. It has the same methods as UsersFactory, but the implementation is different (fake) of course.
I would like to inject UsersFactoryMock, in order to be able myApp.run to use it instead of UsersFactory.
I was trying to do so using beforeEach:
beforeEach(module(function ($provide, $injector)
{
$provide.service("UsersFactory", $injector.get("UsersFactoryMock") );
}));
But running the test, it tells me,
Error: [$injector:modulerr] Failed to instantiate module function ($provide) due to: ReferenceError: UsersFactoryMock is not defined"
How could I achieve my goal?
Thanks in advance.
Does
UsersFactoryMock
need to be registered with the injector? Why not just provide a plain object as your mock?Moreover, testing code in a run block is generally messy. You should move such logic into a service which can then be tested like any other. See: https://stackoverflow.com/a/18089426/2943490.