2

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

测试:我提供了我的指令所需的服务功能的完整模拟。在调试模式下(通过添加断点)运行测试时,一切似乎都是正确的。到目前为止尝试过:降低指令的优先级,起诉 $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)
4

1 回答 1

3

解决方案:

您需要通过将超时设置为 0 来在 AngularJS $digest 循环之外进行断言:

    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)
于 2013-11-11T10:34:36.673 回答