【问题标题】:Trigger click event on an AngularJS directive in Mocha test suite在 Mocha 测试套件中触发 AngularJS 指令的点击事件
【发布时间】:2014-10-31 12:53:16
【问题描述】:

我有一个带有指令的常规角度应用程序。该指令包含一个带有ng-click="clickFunction()" 调用的元素。当我单击该元素时,一切正常。我现在需要为此单击编写一个测试,确保在单击元素时实际运行了此函数 - 这就是我遇到的问题。

这是一个 jsfiddle 来说明我的问题:http://jsfiddle.net/miphe/v0ged3vb/

控制器包含一个函数clickFunction(),应该在点击时调用。单元测试应该模拟对指令元素的单击,从而触发对该函数的调用。

clickFunction 用 sinonjs 模拟,以便我可以检查它是否被调用。该测试失败,意味着没有点击。

我在这里做错了什么?

我已经看到了类似问题的答案,例如 Testing JavaScript Click Event with Sinon,但我不想使用完整的 jQuery,而且我相信我在模拟(监视)正确的函数。


这是上面小提琴中的 js(对于那些喜欢在这里看到它的人):

angular.jsangular-mocks.js 也已加载。

// App
var myApp = angular.module('myApp',[]);

myApp.controller('MyCtrl', function($scope) {
    $scope.person = 'Mr';
    $scope.clickFunction = function() {
        // Some important functionality
    };
});

myApp.directive('pers', function() {
    return {
        restrict: 'E',
        template: '<h2 ng-click="clickFunction()" ng-model="person">Person</h2>',
    };
});

// Test suite
describe('Pers directive', function() {
    var $scope, $controller, template = '<pers></pers>', compiled;
    beforeEach(module('myApp'));

    beforeEach(inject(function($rootScope, $controller, $compile) {
        $scope = $rootScope.$new();
        ctrl = $controller('MyCtrl', {$scope: $scope});
        compiled = $compile(template)($scope);

        // Do I need to run a $scope.$apply() here?
        console.log($scope.$apply); // This is a function, apparently.
        //$scope.$apply();            // But running it breaks this function.
    })); 

    it('should render directive', function() {
        el = compiled.find('h2');
        expect(el.length).to.equal(1);
    });

    it('should run clickFunction() when clicked', function() {
        el = compiled.find('h2');
        sinon.spy($scope, 'clickFunction');

        // Here's the problem! How can I trigger a click?
        //el.trigger('click');
        //el.triggerHandler('click');
        expect($scope.clickFunction.calledOnce).to.be.true
    });
});

// Run tests
mocha.run();

【问题讨论】:

    标签: angularjs angularjs-scope mocha.js dom-events jqlite


    【解决方案1】:

    原来问题很隐蔽。

    首先$scope.$digest$scope.$apply 函数破坏了beforeEach 函数,最终导致了整个解决方案。

    解决方案

    不要混合有角度的版本。

    这就是问题的全部,并且给了我相当模糊的错误。

    感谢 freenode 上#AngularJS IRC 频道的 Foxandxss。


    使用 jQlite 在指令上触发事件的方法很简单:

    someElement.triggerHandler('click');

    【讨论】:

      猜你喜欢
      • 2013-04-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-25
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多