3

我在AngularJS中创建了enter 事件指令,因此我想为该指令运行测试用例。但我不知道如何为输入事件编写代码。

describe('Unit Test: Enter Event', function() {
var elm, compile, scope;    

beforeEach(function() {
    module('att.sandbox.attEnterEvent');
    inject(function($compile, $rootScope) {
        compile = $compile;
        scope = $rootScope.$new();
    });
});

/*scenarion 1*/
it("Enetr Key should call the method inside controller", function() {
    elm = angular.element('<input type="text" att-enter-event="enterEvent()">');
    elm = compile(elm)(scope);
    scope.$digest();
    scope.enterEvent = jasmine.createSpy();

     //**Here i want to add enter event test case** 

     expect().toHaveBeenCalled();
});
})

4

1 回答 1

3

最重要的是:

  • 创建事件对象
  • 修改指令
  • 写测试

创建事件并在元素上触发它

var ev = jQuery.Event("keydown", {
   keyCode: 13
});

el.trigger(ev); // as el is reference to compiled directive

// ---IMPLEMETATION-----------------
angular.module('att.sandbox.attEnterEvent', [])
  .directive('hitEnterEvent', function() {
    return {
      restrict: 'A',
      scope: {
        hitEnterEvent: '&'
      },
      link: function(scope, element, attrs) {
        element.bind("keydown keypress", function(event) {
          if (event.which === 13 || event.keyCode === 13) {
            scope.$apply(function() {
              scope.hitEnterEvent()
            });
            event.preventDefault();
          }
        });
      }
    };
  })
  .controller('hitEntereventCtrl', function($scope) {
    $scope.showinputtext = false;
    $scope.enterEvent = function() {
      $scope.showinputtext = true;
    };
  });

// ---SPECS-------------------------
describe('Unit Test: Enter Event', function() {
  var el, scope;

  beforeEach(function() {
    module('att.sandbox.attEnterEvent');
    inject(function($compile, $rootScope) {
      scope = $rootScope.$new();
      el = $compile(angular.element('<input type="text" hit-enter-event="enterEvent()">'))(scope);
    });
  });

  it("Enter key should call the method inside controller", function() {
    scope.enterEvent = jasmine.createSpy('enterEvent');

    var enterKey = jQuery.Event("keydown", {
      keyCode: 13
    });

    el.trigger(enterKey);

    expect(scope.enterEvent).toHaveBeenCalled();
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<link href="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine.css" rel="stylesheet" />
<script src="//safjanowski.github.io/jasmine-jsfiddle-pack/pack/jasmine-2.0.3-concated.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular-mocks.js"></script>

于 2014-07-24T11:33:35.653 回答