2016-02-27 161 views
0

我創建了一個單元測試對我的指導與角1.4.4:爲什麼測試時範圍值沒有設置?

angular.module('myApp', []) 
    .directive('uiList', [ 
     function() { 
      return { 
       scope: { 
        lengthModel: '=uiList' 
       }, 
       link: function(scope, elm, attrs) { 


        scope.$watch('lengthModel', function(newVal) { 
         scope.test=2; 
         console.log('kut'); 

        }); 
       } 
      }; 
     } 
    ]); 

這是我的測試:

describe('Testing $emit in directive', function() { 
    var scope; 
    var element; 
    var elementScope; 

    beforeEach(module('myApp')); 

    beforeEach(inject(function($rootScope, $compile) { 
     scope = $rootScope.$new(); 
     scope.row = 1; 
     element = angular.element('<ul id="rows" ui-list="row">'); 
     $compile(element)(scope); 
     scope.$digest(); 
     elementScope = element.scope(); 
    })); 

    it('should change value', function() { 

     scope.$apply(function() { 
      scope.row = 1; 
     }); 

     expect(elementScope.test).toEqual(2); 


    }); 

}); 

當我在webstorm運行測試我得到這個錯誤:

Chrome 48.0.2564 (Mac OS X 10.10.5) Testing $emit in directive should emit FAILED    
     Expected undefined to equal 2. 

我到達指令的監視部分,因爲當我運行業力時,我可以看到日誌(= kut)。我怎樣才能通過考試?

回答

1

您已定義指令使用一個孤立的範圍,所以我想scope()你應該isolateScope(),而不是讓你的指令創建隔離範圍的一些元素

elementScope = element.isolateScope(); 

而且你要指派/更新上row屬性,而您應該在控制器的父級範圍上指定/更新row屬性,並按照您指定的方式使用lengthModel: '=uiList'爲您的lengthModel指定雙向綁定。

如在example中所示,我建議您獲取對隔離範圍的引用,更新其中的一些屬性並查看它們是否反映在您之前緩存的原始範圍對象中。

it('sample test case', function(){  

    var isolatedScope = element.isolateScope(); 
    isolatedScope.lengthModel = 10; 

    expect(scope.test).toBe(1); 
}); 
相關問題