我目前正在开发一个大型的AngularJS应用程序,非常基于John Papa所写的 AngularJS Styleguide。
他的建议之一是使用
我面临的问题是,在不运行
如何在不运行
他的建议之一是使用
activate()
方法作为每个控制器的引导程序。这使得您的代码结构清晰,并且您可以立即知道引导程序从哪里开始。通常情况下,我使用它来加载数据(我更喜欢这种方式而不是路由解析)。我面临的问题是,在不运行
activate()
方法的情况下,如何对下面代码示例中的methodUnderTest()
方法进行单元测试。(function() {
'use strict';
angular
.module('myApp', [])
.controller('ControllerUnderTest', ControllerUnderTest);
ControllerUnderTest.$inject = [];
/* @ngInject */
function ControllerUnderTest() {
var vm = this;
// attach functions to vm
vm.activate = activate;
vm.methodUnderTest = methodUnderTest;
// activate
activate();
function activate() {
// controller start-up logic
}
function methodUnderTest() {
// how to test this method, without running the activate() method
}
})();
以下是我目前拥有的测试代码,但正如你所预期的那样,它将总是运行activate()
方法(这不是我想要的)。
(function() {
var scope, createController;
beforeEach(module('myApp'));
describe('ControllerUnderTest', function(){
beforeEach(inject(function($rootScope, $controller) {
scope = $rootScope.$new();
createController = function() {
return $controller('ControllerUnderTest', { 'scope': scope });
};
}));
it('should be defined', function() {
var controller = createController();
expect(controller).toBeDefined();
});
it('should have a methodUnderTest', function() {
var controller = createController();
expect(controller.methodUnderTest).toBeDefined();
});
});
})();
如何在不运行
activate()
方法的情况下测试ControllerUnderTest.methodUnderTest()
?
activate()
方法中有很多事情发生,并且涉及许多不相关的依赖项(服务),这些依赖项并不对methodUnderTest
有用,该怎么办? - Vadiem Janssens