admin管理员组文章数量:1336624
I'm using Jasmine to unit test my Angular App. How can I test form validation in my controller? For example, I have a login function:
$scope.login = function() {
if($scope.form_login.$valid) {
//send request with username and password
};
};
I'm trying to set $valid
to true
, but I can't access the form here. I got an error 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();
})
I'm using Jasmine to unit test my Angular App. How can I test form validation in my controller? For example, I have a login function:
$scope.login = function() {
if($scope.form_login.$valid) {
//send request with username and password
};
};
I'm trying to set $valid
to true
, but I can't access the form here. I got an error 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();
})
Share
Improve this question
edited Apr 29, 2016 at 2:04
WilHall
12k6 gold badges34 silver badges54 bronze badges
asked Apr 29, 2016 at 2:00
vincentfvincentf
1,4992 gold badges20 silver badges39 bronze badges
2 Answers
Reset to default 3Unit test should not really test the form. To test the form and other not controller related things use e2e testing.
However if you really want to test validation in unit test see To test a custom validation angularjs directive or How to unit test angularjs form?
If you uses a service for save the data
$scope.login = function() {
if($scope.form_login.$valid) {
//send request with username and password
MyService.login();
};
};
Check if your service have not been called and mock the $scope.form_login.$valid property to 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();
});
本文标签: javascriptAngularjshow to unit test form validationStack Overflow
版权声明:本文标题:javascript - Angularjs - how to unit test form validation - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742408263a2469263.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论