这里是一些 Javascript,它在 AngularJS 指令的 link
函数中调用 jqLite 的 trigger
。
angular.
module('myApp').
directive('myDirective',
function($timeout) {
return {
link: function(scope) {
scope.resetChosenElements = function() {
$timeout(function() {
$('[chosen]').trigger('chosen:updated');
}, 0);
}
scope.resetChosenElements();
}
};
}
);
如何编写一个测试来检查在创建指令时是否调用了 trigger
而不监视 $.trigger
? (我不想监视 $.trigger
,因为它会捕获对它的所有调用,包括那些来自其他指令的调用)。
有没有办法监视可以传递给 link
的 element
参数?
编辑:我关于监视 element
的评论似乎引起了混淆。我只是在暗示,如果解决方案需要将 element
添加到传递给 link
的参数中,那就没问题了。但是目前我对它没有任何用处,这就是为什么它被排除在参数列表之外的原因。
最佳答案
Rathen 模拟 trigger
函数,您可以监视 element
的事件函数,如 @Michael Benford说你没有在你的代码示例中使用 element
,考虑到你的问题似乎令人困惑:
此示例使用 ChaiJS作为断言工具和SinonJS作为 spies/stubs/mocks 库 你应该在 element
customEvent
spy
beforeEach(inject(function($rootScope, $compile, _$httpBackend_) {
$scope = $rootScope.$new();
compile = $compile;
$httpBackend = _$httpBackend_;
el = angular.element('<elementTemplateTag></elementTemplateTag>');
compile(elm)($scope);
spy = sinon.spy(el, "customEvent"); // Add spy on the event call
}));
afterEach(function(){
el.customEvent.restore(); //clean spy calls
});
it('element.customEvent() called once', function() {
el.trigger('customEvent');
$timeout.flush(); // release all timeouts
expect(el.customEvent.calledOnce()).to.be.true;
});
我希望这对你有用。
关于angularjs - 如何在链接阶段测试指令?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30006943/