![](/img/trans.png)
[英]Using controllerAs syntax in Angular, how can I watch a variable?
[英]Unit testing Angular controller using capture variable for 'this' with controllerAs syntax
我一直在遵循John Pappa撰写的Angular样式指南 ,并且在用controllerAs语法进行测试时遇到了问题。 该指南特别指出要使用捕获变量,例如var vm = this;
以避免将东西附加到控制器内部的$ scope上。
我开始使用此捕获变量测试控制器时遇到问题。 在单元测试中创建控制器时,无法调用附加到捕获变量的方法。
我的代码如下:
控制器:
(function(){
'use strict';
/**
* @ngdoc function
* @name mytodoApp.controller:MainCtrl
* @description
* # MainCtrl
* Controller of the mytodoApp
*/
angular.module('mytodoApp')
.controller('MainCtrl', function ($scope) {
/* jshint validthis: true */
var vm = this;
vm.tasks = [];
vm.addTask = addTask;
vm.removeTask = removeTask;
function addTask() {
if(!contains(vm.tasks, $scope.task)){
vm.tasks.push($scope.task);
} else {
vm.isInvalid = true;
}
$scope.task = '';
};
function removeTask(index) {
vm.tasks.splice(index, 1);
};
var contains = function(list, item) {
var res = list.indexOf(item);
return res === -1 ? false : true;
};
});
})();
单元测试:
'use strict';
describe('Controller: MainCtrl', function () {
// load the controller's module
beforeEach(module('mytodoApp'));
var MainCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
MainCtrl = $controller('MainCtrl', {
$scope: scope
// place here mocked dependencies
});
}));
it('should attach a list of tasks to the viewmodel', function () {
expect(MainCtrl.tasks.length).toBe(0);
});
it('should add items to the list', function() {
scope.task = 'example task';
MainCtrl.addTodo();
expect(MainCtrl.tasks.length).toBe(1);
});
});
我收到此错误:
PhantomJS 1.9.8 (Mac OS X 0.0.0) Controller: MainCtrl should add items to the list FAILED
TypeError: 'undefined' is not a function (evaluating 'MainCtrl.addTodo()')
at /Users/kyle/Code/AngularProjects/mytodo/test/spec/controllers/main.js:28
MainCtrl
没有addTodo()
函数。 您是要运行addTask()
吗?
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.