【问题标题】:How to mock config-phase providers for unit tests?如何模拟单元测试的配置阶段提供程序?
【发布时间】:2015-12-07 13:05:41
【问题描述】:

我正在编写一个规范,检查在被测 Angular 模块的配置阶段调用的方法。

下面是正在测试的代码的简化视图:

angular.module('core',['services.configAction'])
    .config(function(configAction){
        configAction.deferIntercept(true);
    });

上面发生的事情是我们定义了一个具有单个依赖项的core 模块。
然后,在core 模块的config 块中,我们在configAction 对象上调用deferIntercept 方法,以使用services.configAction

我正在尝试测试core 的配置是否调用了该方法。

这是当前设置:

describe('core',function()
{
    const configActionProvider={
        deferIntercept:jasmine.createSpy('deferIntercept'),
        $get:function(){
            return {/*...*/}
        }
    };

    beforeEach(function()
    {
        module(function($provide)
        {
            $provide.provider('configAction',configActionProvider);
        });

        module('core.AppInitializer');

        inject(function($injector)
        {
            //...
        });
    });

    it('should call deferIntercept',function()
    {
        expect(configActionProvider.deferIntercept).toHaveBeenCalledWith(true);
    });
});

问题在于它没有覆盖configAction,因此永远不会调用间谍,原始方法是。
如果我将它作为core 模块的依赖项删除,它将这样做,因此angular.module('core',[]) 而不是angular.module('core',['services.configAction']) 将起作用并调用间谍。

知道如何在测试期间覆盖services.configAction 而不将其从依赖项列表中删除吗?

【问题讨论】:

    标签: angularjs unit-testing angular-providers


    【解决方案1】:

    看看 - https://dzone.com/articles/unit-testing-config-and-run。 类似于以下内容 -

    module('services.configAction', function (configAction) {
      mockConfigAction = configAction;
      spyOn(mockConfigAction, 'deferIntercept').andCallThrough();
    });
    module('core');
    

    在你的 beforeEach 中可能会完成这项工作。

    【讨论】:

    • 谢谢。 [额外字符]
    猜你喜欢
    • 2015-08-24
    • 1970-01-01
    • 1970-01-01
    • 2018-02-05
    • 2014-08-22
    • 2016-11-29
    • 1970-01-01
    • 2015-11-03
    • 2016-02-03
    相关资源
    最近更新 更多