gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-03 04:57:40 24 4
gpt4 key购买 nike

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

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

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

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

我在这里做错了什么?

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

<小时/>

这是上面 fiddle 中的 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();

最佳答案

事实证明问题非常隐蔽。

首先,$scope.$digest$scope.$apply函数打破了beforeEach函数,最终形成了整个解决方案。

解决方案

不要混合 Angular 版本。

这就是整个问题,并给了我相当晦涩的错误。

感谢 freenode 上 #AngularJS IRC channel 的 Foxandxss。

<小时/>

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

someElement.triggerHandler('click');

关于angularjs - 在 Mocha 测试套件中触发 AngularJS 指令上的点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26675196/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com