7

Given 和 AngularJS 应用程序:

名为“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>

一个名为 'LoginController' 的控制器,具有 $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 ...
}

如何为 $scope.LoginForm.$invalid 编写 Jasmine 测试?

我发现它是一个只读属性,所以我尝试在 $scope 上设置一个模拟对象:

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

上面仍然通过了验证,即使它不应该有,因为这两个字段都是必需的。

4

1 回答 1

1

您可以在单元测试中将 $invalid 属性设置为 true:

$scope.LoginForm.$invalid = true;

于 2013-07-05T21:10:19.973 回答