加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

在Mocha测试套件中的AngularJS指令上触发单击事件

发布时间:2020-12-17 17:45:36 所属栏目:安全 来源:网络整理
导读:我有一个带有指令的常规角度应用程序.该指令包含一个带有ng-click =“clickFunction()”调用的元素.单击该元素时,一切正常.我现在需要为此单击编写一个测试,确保在单击该元素时实际运行此函数 – 这就是我遇到的问题. 这是一个解释我的问题的方法:http://js
我有一个带有指令的常规角度应用程序.该指令包含一个带有ng-click =“clickFunction()”调用的元素.单击该元素时,一切正常.我现在需要为此单击编写一个测试,确保在单击该元素时实际运行此函数 – 这就是我遇到的问题.

这是一个解释我的问题的方法:http://jsfiddle.net/miphe/v0ged3vb/

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

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

我在这做错了什么?

我已经看到类似问题的答案,如Testing JavaScript Click Event with Sinon,但我不想使用完整的jQuery,我相信我正在嘲笑(监视)正确的功能.

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

angular.js,angular-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,$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();

解决方法

事实证明这个问题很隐蔽.

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

不要混合角度版本.

>在the first fiddle

> angular.js版本1.3.0
> angular-mocks.js版本1.1.5

>在the solved fiddle年

> angular.js版本1.3.0
> angular-mocks.js版本1.3.0

这就是整个问题,给了我相当模糊的错误.

感谢来自freenode上#AngularJS IRC频道的Foxandxss.

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

someElement.triggerHandler( ‘点击’);

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读