我正在使用Jasmine对我的Angular App进行单元测试。如何在控制器中测试表单验证?例如,我有一个登录功能:
$scope.login = function() {
if($scope.form_login.$valid) {
//send request with username and password
};
};
我正在尝试将$valid
设置为true
,但我无法在此处访问该表单。我收到了错误TypeError: Cannot set property '$valid' of undefined
:
it('should not send request if form validation fails', function() {
$controller('loginController', {$scope: $scope});
$scope.form_login.$valid = true;
$scope.login();
})
答案 0 :(得分:2)
单元测试不应该真正测试表单。要测试表单和其他非控制器相关的东西,请使用e2e测试。
但是,如果您真的想在单元测试中测试验证,请参阅To test a custom validation angularjs directive或How to unit test angularjs form?
答案 1 :(得分:1)
如果您使用服务保存数据
$scope.login = function() {
if($scope.form_login.$valid) {
//send request with username and password
MyService.login();
};
};
检查您的服务是否未被调用,并将$ scope.form_login。$ valid属性模拟为false;
var MyService, controllerInjector, rootScope;
beforeEach(inject(function($controller, _MyService_, $rootScope){
controllerInjector = $controller;
MyService = _MyService_;
rootScope = $rootScope;
}))
it('should not send request if form validation fails', function() {
var scope, controller;
scope = rootScope.$new();
scope.form_login = {
$valid : false;
}
var loginController = controllerInjector('loginController', {
$scope : scope
});
spyOn(MyService,'login');
scope.login();
expect(MyService.login).not.toHaveBeenCalled();
});