如何使用Jasmine和Phantomjs在Angular单元测试中触发'keyup'事件

时间:2015-10-15 16:25:14

标签: angularjs jasmine phantomjs keyup eventtrigger

我想测试我的指令,这里是:

function passwordMatch($timeout) {
  return {
    require: 'ngModel',
    link: function (scope, elem, attrs, ctrl) {
      var firstPassword = '#' + attrs.passwordMatch;
      elem.add(firstPassword).on('keyup', function () {
        scope.$apply(function () {
          var isMatch = elem.val() === $(firstPassword).val();
          $timeout(function(){
            ctrl.$setValidity('passwordMatch', isMatch);
          })
        });
      });
    }
  }
}

要测试'passwordMatch'指令,我需要在我的jasmine测试文件中触发'keyup'事件。 这是我的茉莉花代码:

describe('directives', function() {
  var scope;
  var compile;
  var form;

  beforeEach(module('formValidation'));
  beforeEach(inject(function(_$compile_, _$rootScope_) {
    scope = _$rootScope_.$new();
    var element = angular.element(
      '<form name="form">' +
      '<input type="email" ng-model="model.email" name="email" email-validate />' +
      '<input ng-model="model.password" name="password" password-validate />' +
      '<input ng-model="model.confirm_password" name="confirm_password" password-match="password" />' +
      '<input ng-model="model.phone" name="phone" number-only />' +
      '<input ng-model="model.zipCode" name="zipCode" contain-number />' +
      '</form>'
    );
    scope.model = {
      email: null,
      password: null,
      confirm_password: null,
      phone: null,
      zipCode: null
    };
    compile = _$compile_;
    compile(element)(scope);
    scope.$digest();
    form = scope.form;
  }));

  describe('passwordMatch', function() {
    it('should not pass without match', function() {
      form.password.$setViewValue('1234567');
      form.confirm_password.$setViewValue('7654321');
      // need trigger 'keyup' event here
      expect(form.confirm_password.$valid).toBe(false);
    });
  });

})

我尝试为此编写单元测试,但我无法成功触发keyup事件。我想知道有谁能解决我的问题。

0 个答案:

没有答案