使用Jasmine测试时在全球范围内注入AngularJS工厂模

使用Jasmine测试时在全球范围内注入AngularJS工厂模

本文介绍了使用Jasmine测试时在全球范围内注入AngularJS工厂模型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为AngularJS应用程序的控制器创建单元测试。
在myapp.run中,我以某种方式注入并使用了一个名为UsersFactory的工厂:

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)
    {
        //..
    });
}]);

我为UsersFactory创建了一个名为UsersFactoryMock的Mock。它具有与UsersFactory相同的方法,但是实现方式是不同的(伪造的)。

I created a Mock for UsersFactory called UsersFactoryMock. It has the same methods as UsersFactory, but the implementation is different (fake) of course.

我想注入UsersFactoryMock,以便使myApp.run能够

I would like to inject UsersFactoryMock, in order to be able myApp.run to use it instead of UsersFactory.

我试图使用beforeEach来做到这一点:

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,

我如何实现我的目标?

预先感谢。

推荐答案

UsersFactoryMock 是否需要向注入器注册?为什么不仅仅提供一个普通对象作为?
您的模拟游戏?

Does UsersFactoryMock need to be registered with the injector? Why not just provide a plain object asyour 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.

这篇关于使用Jasmine测试时在全球范围内注入AngularJS工厂模型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-03 15:19