如何模拟配置阶段提供程序进行单元测试?

时间:2015-12-07 13:05:41

标签: angularjs unit-testing angular-providers

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

这里简要介绍了正在测试的代码:

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

以上是我们定义一个具有单一依赖关系的core模块 然后,在config模块的core - 块中,我们在deferIntercept上使用configAction对象调用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而不从依赖列表中删除它吗?

1 个答案:

答案 0 :(得分:5)

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

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

在你的之前可能会做这个工作。