gpt4 book ai didi

javascript - AngularJS:指令限制: 'E' 阻止在 Jasmine 单元测试中调用元素 click() 事件

转载 作者:搜寻专家 更新时间:2023-11-01 04:32:01 25 4
gpt4 key购买 nike

这里有一些指令和单元测试。

这是第一个指令:

directive('myTestDirective', function() {
return {
link: function(scope, element, attrs) {
element.on("click", function(e) {
scope.clicked = true;
console.log("clicked");
}
}
});

单元测试:

describe('my test directive', function() {
beforeEach(function() {
.....
inject($compile, $rootScope) {
scope = $rootScope.$new();
html = '<div my-test-directive></div>';
elem = angular.element(html);
compiled = $compile(elem);
compiled(scope);
scope.$digest();
}
});
it('should set clicked to true when click() is called', function() {
elem[0].click();
expect(scope.clicked).toBe(true);
});
});

当上面的单元测试运行时,测试通过并且clicked被记录到控制台。

但是,请考虑添加了 restrict: E 的指令:

directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
element.on("click", function(e) {
scope.clicked = true;
console.log("clicked");
}
}
});

单元测试:

describe('my directive', function() {
beforeEach(function() {
.....
inject($compile, $rootScope) {
scope = $rootScope.$new();
html = '<my-directive></my-directive>';
elem = angular.element(html);
compiled = $compile(elem);
compiled(scope);
scope.$digest();
}
});
it('should set clicked to true when click() is called', function() {
elem[0].click();
expect(scope.clicked).toBe(true);
});
});

这个测试失败了。 clicked 未记录到控制台。从调试中我可以看到绑定(bind)指令的 click() 绑定(bind)的函数没有被执行。

如何继续使用 restrict : 'E',同时仍然保留在单元测试中模拟点击的能力?

更新:感谢 Michal 的 plunkr,我让它工作了。

我将 inject() 函数更改为:

inject(function($compile, $rootScope, $document) {
scope = $rootScope.$new();
html = '<my-test-directive-element></my-test-directive-element>';
elem = angular.element(html);
$compile(elem)(scope);
scope.$digest();
});

在此之后,单击使用限制属性和限制元素都起作用。

Plukr 在这里: http://plnkr.co/edit/fgcKrYUEyCJAyqc4jj7P

最佳答案

使用 jqLit​​e on('click') 不是很 Angular-ish 我不认为它会被 Angular 摘要循环处理(因此无论你在那个回调中添加到你的范围都不会在你的DOM,除非您手动执行)。你应该更喜欢在你的内部使用内置的 ng-click 指令,所以 html 代码变成:

<my-directive ng-click="onClick()"></my-directive>

和你的指令:

directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.onClick = function() {
scope.clicked = true;
console.log("clicked");
}
}
}
});

关于javascript - AngularJS:指令限制: 'E' 阻止在 Jasmine 单元测试中调用元素 click() 事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20670304/

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