编辑:该指令的编译似乎是在测试失败之后进行的。
测试:我提供了我的指令所需的服务函数的完整模拟。当在调试模式下运行测试时(通过添加一个断点),一切似乎都是正确的。到目前为止已经尝试过:减少指令的优先级,起诉$digest而不是编译,以及许多其他。
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)发布于 2013-11-11 10:34:36
解决方案:
您需要在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)https://stackoverflow.com/questions/19893136
复制相似问题