如何在Angular中测试表单验证

时间:2013-12-11 00:50:19

标签: validation angularjs testing jasmine end-to-end

我正在尝试围绕使用Angular的表单编写测试。

在关注this solution之后,我可以在e2e测试中访问表单的范围。现在使用此代码:

scope('Form', function(scope) {
    scope.email = "test@test.com";
    scope.password = "abcd1234";

    expect(scope.form.$valid).toBe(true);
})

无论出于何种原因,scope.form.$valid都是假的。如果我将其包裹在setTimeout()内,它的效果非常好。 Angular的sleep()方法毫无用处。

任何指针?

2 个答案:

答案 0 :(得分:2)

您应该$digest在最后一个scope.password之后添加scope.$digest()的范围。

答案 1 :(得分:0)

感谢mimo的建议,我找到了最终解决方案。

必须构建自定义dsl语句,以便愚弄expect以获取未来。

angular.scenario.dsl('expectScope', function() {
  var _retrieve = function(source, target) {
      if(target == '') return source;
      var targets = target.split('.');
      var nextTarget = targets[0];
      return _retrieve(source[nextTarget], targets.splice(1).join('.') );
  };
  var chain = angular.extend({}, angular.scenario.matcher);

  chain.not = function() {
      this.inverse = true;
      return chain;
  };

  return function(scope, name) {
      this.future = new angular.scenario.Future('scope.'+name, function() {});
      this.future.value = _retrieve(scope, name);
      return chain;
  };
});

scope.$digest之前调用expectScope(scope, 'value.othervalue'),现在一切都按预期工作。