gpt4 book ai didi

angularjs - 测试在 $compile 期间更改 HTML 节点元素的指令

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

编辑:似乎指令的编译发生在测试已经失败之后。

测试:
我提供了指令所需的服务功能的完整模拟。
在 Debug模式下(通过添加断点)运行测试时,一切似乎都是正确的。
到目前为止尝试过:
降低指令的优先级,起诉 $digest 而不是 compile 等等。

  describe('restrict', function(){
var scope, compile, html, elem, authService;
html = '<span data-restrict data-access="admin"></span>';
beforeEach(function(){
module('myApp.directives');
module('myApp.services');
inject(function($compile, $rootScope, $injector){
authService = $injector.get('authService');
authService.setRole('guest');
scope = $rootScope.$new();
compile = $compile;
});
});
it('should allow basic role-based content discretion', function(){
expect(elem.length).toEqual(0);
console.log(elem);//HTML node
timeout(function(){
console.log(elem);//undefined
}, 500);
});
});

指令:
angular.module('myApp.directives', []).
directive('restrict', function(authService){
return{
restrict: 'A',
prioriry: 100000,
scope: false,
compile: function(element, attr, linker){
debugger;//The test has already failed one I reach this break point!
var accessDenied = true;
var user = authService.getUser();
var attributes = attr.access.split(" ");
for(var i in attributes){
if(user.role == attributes[i]){
accessDenied = false;
}
}

if(accessDenied){

angular.forEach(element.children(), function(elm){
try{
elm.remove();
}
catch(ignore){}
});//TODO: find a better solution for IE or remove this code

element.children().remove();
element.remove();
}

}
}
});

测试输出:
Chrome 30.0.1599 (Linux) restrict should allow basic role-based content discretion FAILED
Expected { 0 : HTMLNode, length : 1 } to equal 0.
Error: Expected { 0 : HTMLNode, length : 1 } to equal 0.
at null.<anonymous> (/var/www/front/dev/angular-seed/test/unit/directivesSpec.js:19:22)

最佳答案

解决方案:

您需要在 AngularJS $digest 循环之外进行断言,方法是将超时设置为 0:

    it('should allow basic role-based content discretion', function(){
timeout(function(){
expect(elem).toBeUndefined();
}, 0);
});
});

测试输出:
Chrome 30.0.1599 (Linux): Executed 2 of 2 SUCCESS (0.537 secs / 0.061 secs)

关于angularjs - 测试在 $compile 期间更改 HTML 节点元素的指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19893136/

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