【发布时间】:2016-02-12 19:30:54
【问题描述】:
我有一个控制器,它在加载相关视图时当前正在调用 RESTful API。因此,我不确定这个问题是否与我正在测试的方式或代码本身的实现有关 - 我会对任何从整体上解决问题的建议感到满意,即帮助我单元 -测试我想要的代码:)
这里有一些例子来说明我的观点:
控制器:
angular.module('app.myModule',[])
.controller('MyController', function($scope) {
$scope.notTestingThis = function() {
var thisFails = $scope.do.not.want.to.mock.these.objects.substr(0,10);
};
$scope.testingThis = function(myString) {
$scope.newString = myString;
};
$scope.notTestingThis();
});
测试(目前):
describe('MyControllerTest', function() {
beforeEach(module('app.myModule'));
var $controller;
beforeEach(inject(function(_$controller_) {
$controller = _$controller_;
}));
describe('$scope.testingThis()', function() {
it('sets newString', function() {
$scope = {
'notTestingThis': {}
};
var myController = $controller('MyController', {$scope: $scope});
});
});
});
加载此视图时,我需要以某种方式调用 notTestingThis 函数,但是在我的单元测试中,我想隔离 testingThis 函数。问题是,当我在测试中初始化控制器时,它当然会调用 notTestingThis 并尝试对不存在的对象执行操作(在此测试中我不关心)。
很明显,按照这个例子尝试存根有问题的函数是没有用的,因为 $scope 将在初始化时被重写。有没有办法在您尝试测试的控制器中存根或模拟单个函数,或者我在某个地方错过了要点?一位同事提出的一些建议是:
增强控制器以了解单元测试本身,允许您根据注入的模拟调整程序流程,即控制器中的以下内容:
if (!$scope.methodA) {
$scope.methodA = function() {...}
}
...或...
改变 notTestingThis 函数的调用方式,通过监听来自 $rootScope 的初始化事件而不是直接调用它,这将允许我模拟 $rootScope 以便它不会触发此事件,从而防止 notTestingThis 被调用
我不禁觉得我在想这个问题。有什么见解吗?
【问题讨论】:
标签: angularjs unit-testing controller stubbing