Globally injecting am AngularJS factory mockup when testing with Jasmine

点点圈 提交于 2019-12-12 04:34:33

问题


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:


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.



来源:https://stackoverflow.com/questions/27249933/globally-injecting-am-angularjs-factory-mockup-when-testing-with-jasmine

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!