首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >测试在$compile期间更改HTML元素的指令

测试在$compile期间更改HTML元素的指令
EN

Stack Overflow用户
提问于 2013-11-10 18:03:51
回答 1查看 1.8K关注 0票数 2

编辑:该指令的编译似乎是在测试失败之后进行的。

测试:我提供了我的指令所需的服务函数的完整模拟。当在调试模式下运行测试时(通过添加一个断点),一切似乎都是正确的。到目前为止已经尝试过:减少指令的优先级,起诉$digest而不是编译,以及许多其他。

代码语言:javascript
复制
  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);
   });
});

指令:

代码语言:javascript
复制
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();           
            }

        }
    }
});

测试输出:

代码语言:javascript
复制
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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2013-11-11 10:34:36

解决方案:

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

代码语言:javascript
复制
    it('should allow basic role-based content discretion', function(){
        timeout(function(){
          expect(elem).toBeUndefined(); 
        }, 0);
    });
  });

测试输出:

代码语言:javascript
复制
Chrome 30.0.1599 (Linux): Executed 2 of 2 SUCCESS (0.537 secs / 0.061 secs)
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/19893136

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档