模拟一个AngularJS模块传递给另一个

时间:2017-01-23 09:40:59

标签: angularjs unit-testing karma-jasmine

我在模拟属于我的某个模块的工厂时遇到了一些麻烦。我想模拟的工厂有2个依赖项:

工厂类:

angular.module('serviceapp')
.factory('claims.service', ['applicationSettings', 'localStorageService', function (applicationSettings, localStorageService) {
    //Factory code here
}]);

测试类:

//Instantiate some values
var mockAppSettings = {};
var mockStorageService = {};
var $factory; //Will hold my factory

//Targeting my module for mocking
beforeEach(angular.mock.module('serviceapp'));

//Providing some values for the dependencies of my module
beforeEach(module('serviceapp', function ($provide) {
    $provide.value('applicationSettings', mockAppSettings);
    $provide.value('localStorageService', mockStorageService);
}));

//Problems start here
beforeEach(inject(function ($injector) {
    $factory = $injector.get('claims.service');
}));

我收到错误消息

Failed to instantiate module serviceapp due to: Failed to instantiate module accountModule due to: Module 'accountModule' is not available!

在调查时,我发现accountModule被列为serviceApp模块的依赖项。

App.module类:

angular.module('serviceapp', [accountModule])

但是我在模拟这个模块传递给serviceapp时遇到了一些麻烦。我试图以与我在开始时模拟serviceapp相同的方式模拟accountModule但是这仍然会出现相同的错误消息。我如何模拟并将一个模块传递给另一个模块?

1 个答案:

答案 0 :(得分:1)

angular.mock.module('serviceapp')不应该按字面意思阅读。它不会模拟模块。它与module('serviceapp')相同,用于保留module的模块化环境中。

所以,那一切

beforeEach(angular.mock.module('serviceapp'));
beforeEach(module('serviceapp', ...));

确实加载serviceapp两次(没有伤害,但也没有帮助)。

为避免Module 'accountModule' is not available!,应该(重新)定义:

beforeAll(() => {
  angular.module('accountModule', [])
});

这种方法的问题在于,即使已经定义,它也会被覆盖到测试运行结束。如果真正的accountModule需要在其他测试中使用,那么这是不可能的。

针对类似设计问题的适当解决方案(这也适用于测试中不需要的依赖项,例如路由器模块)

angular.module('serviceapp', ['accountModule']);

angular.module('serviceapp.internal', [])
.factory('claims.service',...);

此处serviceapp用作serviceapp.internal的浅包装,而后者可以安全地进行测试。如果serviceapp是用于引导的顶级模块,则表明应用程序没有足够的模块化,这会对测试造成伤害。

相关问题