【发布时间】:2017-09-25 15:12:43
【问题描述】:
我有一个 Angular 1.5 项目,其中包含许多模块,每个模块可能依赖于其他模块。尝试对作为模块一部分的控制器进行单元测试时,我会像这样导入模块:
angular.mock.module('SaidModule');
...然后在需要的地方提供并注入它的服务。
问题在于SaidModule 依赖于AnotherModule1、AnotherModule2、AnotherModule3....
angular.module('SaidModule', ['AnotherModule1', 'AnotherModule2', 'AnotherModule3']);
所以很自然,当我调用 SaidModule 时,其他模块也会被调用,这超出了单元测试的范围
在单元测试中我尝试了以下解决方案
angular.module('AnotherModule1',[]);
angular.module('AnotherModule2',[]);
angular.module('AnotherModule3',[]);
angular.mock.module('SaidModule');
虽然对于当前的单元测试,我已经成功解耦了依赖关系,但我也销毁了 实际的 AnotherModule1、AnotherModule2、AnotherModule3 所以当轮到它进行单元测试时,它们是 在我看来正确的角度项目中甚至都看不到。因为我使用 angular.module 来定义一个 恰好覆盖实际模块的新模块。 不过,这里也建议使用此解决方案模拟模块依赖项
在 Angular 文档中,它指出请参阅 Angular 文档模拟模块 如果传递了一个对象文字,每个键值对将通过 $provide.value 在模块上注册, 键是与注入器上的值相关联的字符串名称(或标记)。
所以在我看来,解决方案以某种方式使用 angular.mock.module 以某种方式覆盖依赖项 模块,但到目前为止我还没有找到解决方案。 非常感谢任何帮助
【问题讨论】:
标签: javascript angularjs unit-testing module mocking