2015-06-29 53 views
0

我需要訪問指令的隔離範圍才能測試它包含的函數。我嘗試了所有從我發現的解決方案。問題在於指令的隔離範圍,因爲如果我不用隔離範圍來設置指令,測試就可以正常工作。無法訪問茉莉花測試中指令的隔離範圍

我的指令看起來像這樣:

angular.module('validators').directive('validateName', [function() { 

    var directive = {}; 

    directive.restrict = "A"; 
    directive.require = 'ngModel'; 
    directive.scope = {}; 

    directive.link = function(scope, element, attrs, ngModel) { 

     scope.checkIfGoodCharactersOnly = function(name) { 

      if (name.match(/[0-9!$%^&*@#()_+|~=`{}\[\]:";'<>?,.\/]/g)) { 
       return false; 
      } else { 
       return true; 
      } 

     }; 

    }; 

    return directive; 

}]); 

測試建立如下:

beforeEach(module('validators')); 

    describe('Directive: validateName', function() { 

     var $scope, elem; 

     beforeEach(

      inject(function ($compile, $rootScope) { 

       $scope = $rootScope.$new(); 

       elem = angular.element('<form name="form">' + 
       '<input name="name" ng-model="transaction.name" validate-name />' + 
       '</form>'); 

       elem = $compile(elem)($scope); 

       $scope = elem.isolateScope(); 

     })); 

     describe("Link", function() { 

      it("Should call checkIfGoodCharactersOnly", function() { 
       expect($scope.checkIfGoodCharactersOnly("abcd")).toEqual(true); 
      }); 

     }); 

    }); 

控制檯輸出:

類型錯誤: 'undefined'不是一個對象(評估'$ scop e.checkIfGoodCharactersOnly')

回答

1

由於表單元素包裝輸入,我試圖訪問表單元素的作用域,它不存在。

這工作:

input = elem.find('input'); 
expect(input.isolateScope()).toBeDefined();