Angularjs - how to unit test form validation

笑着哭i 提交于 2019-12-04 11:23:43
Alex Ryltsov

Unit 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();

});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!