Angularjs - how to unit test form validation

I am using Jasmine for unit test my Angular App. How can I check 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 am trying to install $validon true, but I cannot access the form here. I got an error message 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();
})
+4
source share
2 answers

Unit test should not really validate the form. To test form and other non-controller elements, use e2e testing.

, unit test . angularjs unit test ?

+2

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

});
+1

All Articles