在没有看到实时代码示例的情况下提供精确的指导有点困难(这就是为什么提供一个具有 Jasmine 测试模板的 plunk 通常是一个好主意),但这听起来像是您的init
方法执行一些设置逻辑,这些逻辑应该根据环境而有所不同。如果是这样,前进的方法是将这个初始化逻辑封装到一个专用服务中,并在测试期间模拟该服务(这正是 @Joe Dyndale 所建议的)。
假设您的控制器如下所示:
app.controller('MainCtrl', function($scope) {
$scope.init = function() {
//something I really don't want to call during test
console.log("I'm executing");
};
});
它可以重构为:
app.factory('InitService', function() {
return {
init = function() {
//something I really don't want to call during test
console.log("I'm executing");
}
};
});
app.controller('MainCtrl', function($scope, InitService) {
InitService.init();
});
然后模拟测试可能如下所示:
describe('Testing an initializing controller', function() {
var $scope, ctrl;
//you need to indicate your module in a test
beforeEach(module('plunker'));
beforeEach(module(function($provide){
$provide.factory('InitService', function() {
return {
init: angular.noop
};
});
}));
beforeEach(inject(function($rootScope, $controller) {
$scope = $rootScope.$new();
ctrl = $controller('MainCtrl', {
$scope: $scope
});
}));
it('should test sth on a controller', function() {
//
});
});
Finally here http://plnkr.co/edit/fgZMJNfPQeKLt0IEva7d?p=preview是 plunker 中的实时代码