Globally injecting am AngularJS factory mockup whe

2019-09-02 20:10发布

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.

1条回答
一夜七次
2楼-- · 2019-09-02 20:51

Does UsersFactoryMock need to be registered with the injector? Why not just provide a plain object as your mock?

var UsersFactoryMock = {
    getMe: function () {
        // mocked method
    }
};

beforeEach(module(function ($provide) {
    $provide.service("UsersFactory", UsersFactoryMock);
}));

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.

查看更多
登录 后发表回答