我正在尝试使用karma和jasmine对连接形式控制器进行单元测试,但是我无法理解这一点。
控制器:
.controller('connectionController', ['$scope', '$rootScope', '$state', '$stateParams', '$http', '$localStorage',
function($scope, $rootScope, $state, $stateParams, $http, $localStorage){
$scope.userCredentials = {};
$scope.connectionError = false;
$scope.connectUser=function(){
if ($scope.connectionForm.$valid) {
//Do the login stuff here
//IF good --> state.go...
}
else {
console.log('Invalide.');
$scope.connectionError = true;
}
}
}])
然后在我的HTML中(简化为最大值):
<form name="connectionForm" novalidate>
<div class="form-group input-group" show-errors='{ showSuccess: true }'>
<span for="login" class="input-group-addon"></span>
<input type="text" ng-model="userCredentials.login" required>
</div>
<div class="form-group input-group" show-errors='{ showSuccess: true }'>
<span for="password" class="input-group-addon"></span>
<input type="password" ng-model="userCredentials.password" required>
</div>
<button class="btn btn-primary" ng-click="connectUser()">Connect</button>
</form>
最后是测试(特定'它'不通过):
it('should connect user', function(){
scope.userCredentials.login = 'aUser';
scope.userCredentials.password = 'aPassword';
$httpBackend.when('POST', 'http://localhost:4711/api/token').
respond({ token: 'xxx', user: aUser });
scope.connectUser();
$httpBackend.flush();
});
所以我得到的问题是:
TypeError: Cannot read property '$valid' of undefined
at Scope.$scope.connectUser (connection.js)
at null.<anonymous> (connection.js)
我认为基本问题来自于控制器无法访问仅在html上定义的内容(如connectionForm ...)并且无法获取其属性。
另一件需要注意的事情是,当连接成功时,我会执行state.go(..),可能是这样吗?
我该怎么办?或者更重要的是,我做错了什么?