【发布时间】:2013-12-29 16:26:16
【问题描述】:
我正在尝试测试我的控制器, 当我运行测试时,我得到:
TypeError: Object # has no method '$watch'
在我的控制器中我使用 $scope.$watch,我该如何解决这个问题?
controllerSpecs.js
describe('controllers', function(){
var scope, ctrl,timeout;
beforeEach(module('controllers'));
beforeEach(inject(function($controller) {
scope = {};
timeout = {};
ctrl = $controller('PublishersCtrl', {$scope:scope,APIService:APIService,$timeout:timeout});
}));
it('should have scope variable equals number', function() {
expect(scope.number).toBe(3);
});
});
controller.js:
controller('PublishersCtrl',['$scope','APIService','$timeout', function($scope,APIService,$timeout) {
$scope.number = 3;
/* Make sure second click on order will revert the sorting */
$scope.$watch('orderByField', function() {
$scope.reverseSort = true;
}); // initialize the watch
APIService.get_publisher_list().then(function(data){
$scope.render_table_and_filters(data);
});
}
错误:
TypeError: Object #<Object> has no method '$watch'
at new <anonymous> (C:/angular-client/app/js/controllers.js:24:12)
【问题讨论】:
-
您正在将
scope初始化为{}。所以,$scope是{}并且没有任何角度方法。只需删除 beforeEach$controller()调用中的范围属性即可。 -
@Utopik 谢谢,现在我得到不同的错误,TypeError: Cannot set property 'number' of undefined I have in my controller $scope.number = 3, but now scope is undefined.
标签: javascript unit-testing angularjs karma-runner karma-jasmine