【发布时间】:2016-07-06 14:01:38
【问题描述】:
我目前正在开发一个大型 AngularJS 应用程序,非常基于优秀的 AngularJS Styleguide by John Papa。
他的一个建议是使用activate() 方法作为每个控制器的引导程序。这使您的代码结构清晰,您立即知道引导从哪里开始。很多时候,我用它来加载数据(我更喜欢这个而不是路由解析)。
我面临的问题是我应该如何在下面的代码示例中对methodUnderTest()-方法进行单元测试而不运行activate()-方法。
(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()?
【问题讨论】:
-
你必须模拟激活方法内部的所有调用,不执行初始化方法不是一个好的测试
-
感谢 fantarama,但是如果
activate()方法中发生了很多事情,并且有很多不同的依赖项(服务),这些对 methodUnderTest 没有用处怎么办? -
对测试无用的服务必须用 void 实现或固定返回值来模拟
-
谢谢Fantarama。如果您在答案中提供您的 cmets,我很乐意将此帖子标记为已回答。
标签: angularjs unit-testing jasmine tdd