Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I unit test for form is/is not valid in Jasmine for AngularJS?

Given and AngularJS app with:

A form named 'LoginForm'

<div class="well well-large loginForm" ng-controller="LoginController" ng-hide="isAuthenticated">
    <form id="loginForm" class="form-signin" name="LoginForm">
        <h2 class="form-signin-heading">Please sign in</h2>
        <input type="text" name="username" ng-model="user.username" required
            class="input-block-level input-large" placeholder="Username" autocorrect="off" autocapitalize="off" tabindex="1">
        <input type="password" name="password" ng-model="user.password" required
            class="input-block-level input-large" placeholder="Password" tabindex="2">
        <p ng-show="error401" class="text-error">Username and/or password was incorrect</p>
        <p ng-show="error500" class="text-error">Whoops! Something went wrong</p>
        <button class="btn btn-primary loginButton" ng-click="login(user)" tabindex="3">Sign in</button>
    </form>
</div>

A controller named 'LoginController', with function of $scope.login()

$scope.login = function(user) {
    if ($scope.LoginForm.$invalid) {
        log('LoginForm is invalid');
        return;
    } else {
        log('LoginForm is valid');
    }
    // ... snip ... other stuff like actual ajax login ...
}

How do I write a Jasmine test for $scope.LoginForm.$invalid?

I have found that it is a readonly property, so I tried to setup a mock object on $scope:

scope.LoginForm = {
    "user" : {
        "password": "something"
    }
};

The above still passed validation, even though it should not have because both fields are required.

like image 593
David Frahm Avatar asked May 22 '13 12:05

David Frahm


1 Answers

You could set the $invalid property to true in your unit test:

$scope.LoginForm.$invalid = true;

like image 83
Mattias Rasmusson Avatar answered Oct 21 '22 05:10

Mattias Rasmusson