如何在指令中触发事件进行测试?

How to trigger event in directive for testing it?

我有一个带有事件处理程序的简单指令。

angular.module('app')
    .directive('acc', function () {
      return {
        restrict: 'A',
        link: function (scope, element) {
            scope.a = 0;
            scope.func = function() {
                console.log('h2.clicked !!');
                scope.a = 1;
            };

          element.on('click', 'h2', scope.func);
        }
      };
    });

和简单测试

describe('Directive: acc', function () {
    beforeEach(module('app'));

    var element,
        scope;

    var clickContext = 'h2';
    var onSpy;

    beforeEach(inject(function ($compile, $rootScope) {
        scope = $rootScope.$new();

        onSpy = spyOn($.fn, 'on').and.callThrough();

        element = angular.element('<nav acc><h2></h2></nav>');
        element = $compile(element)(scope);
        scope.$digest();
    }));

    it('should set click handler', function () {
        expect(onSpy).toHaveBeenCalledWith('click', clickContext, jasmine.any(Function));
    });

    describe('click handler behaviour', function () {

        beforeEach(function () {
            element.find('h2').triggerHandler('click');
        });


        it('handler should be called', function () {
          expect(scope.a).toBe(1);
        });
    });
});

我想在每个测试用例之前调用处理程序来验证行为。 怎么做? 我使用 jasmine 进行单元测试。

您是否尝试过在 .click() 之后调用 scope.$digest();