12

単体テストを単体テストしようとしていますが、スコープ内の変数が常に定義されていません。ディレクティブで単体スコープの単位テストを行う方法

指令のSrcコード:

.directive('ratingButton', ['$rootScope', 


function($rootScope) { 
     return { 
      restrict: "E", 
      replace: true, 
      template: '<button type="button" class="btn btn-circle" ng-class="getRatingClass()"></button>', 
      scope: { 
       buttonRating: "=" 
      }, 
      link: function(scope, elem, attr) { 
       scope.getRatingClass = function() { 
        if (!scope.buttonRating) 
         return ''; 
        else if (scope.buttonRating.toUpperCase() === 'GREEN') 
         return 'btn-success'; 
        else if (scope.buttonRating.toUpperCase() === 'YELLOW') 
         return 'btn-warning warning-text'; 
        else if (scope.buttonRating.toUpperCase() === 'RED') 
         return 'btn-danger'; 
        else if (scope.buttonRating.toUpperCase() === 'BLUE') 
         return 'btn-info'; 
       } 
      } 
     }; 
    }]) 

試験:

describe('Form Directive: ratingButton', function() { 

    // load the controller's module 
    beforeEach(module('dashboardApp')); 

    var scope, 
     element; 

    // Initialize the controller and a mock scope 
    beforeEach(inject(function($compile, $rootScope) { 
     scope = $rootScope.$new(); 

     //set our view html. 
     element = angular.element('<rating-button button-rating="green"></rating-button>'); 
     $compile(element)(scope); 
     scope.$digest(); 
    })); 

    it('should return appropriate class based on rating', function() { 
     //console.log(element.isolateScope()); 
     expect(element.isolateScope().buttonRating).toBe('green'); 
     expect(element.isolateScope().getRatingClass()).toBe('btn-success'); 

    }); 

}); 

私は要素の属性を介して値を渡すことであった別の指示ユニットテストで同様のコードを使用し、予想通り、それが働きました。このテストボタンのためには、評価は未定義です。ここからどこに行かないかはわかりません(私はジャスミン/カルマでかなり新しいです)

助けがあれば助かります!

答えて

24

文字列を設定する代わりに、​​は、テストの起動時に指示要素がコンパイルされたときに範囲に設定されます。それ以外の場合は、範囲スコープ上の​​という名前のスコーププロパティの値を検索します。もちろん、あなたの場合は定義されていません。

すなわちscope.buttonRating = 'green';

angular.element('<rating-button button-rating="buttonRating"></rating-button>')

試してみてください。それが働いたよう

// Initialize the controller and a mock scope 
    beforeEach(inject(function($compile, $rootScope) { 
     scope = $rootScope.$new(); 
     scope.buttonRating = 'green'; //<-- Here 
     //set our view html. 
     element = angular.element('<rating-button button-rating="buttonRating"></rating-button>'); 
     $compile(element)(scope); 
     scope.$digest(); 
    })); 

    it('should return appropriate class based on rating', function() { 
     expect(element.isolateScope().buttonRating).toBe('green'); 
     expect(element.isolateScope().getRatingClass()).toBe('btn-success'); 

    }); 

Plnkr

+0

ああ見えます。なぜ私はそれを考えなかったのか分かりません! – atsituab

+0

心配することはありません。:) – PSL

+1

ughは、これで多くの時間を無駄にしました。 @のためにうまくいきましたが、リテラル文字列をそこに置くことができないことは分かりませんでした(それはUNBINDABLEです)。嬉しいAngular 2は、ボンネットの下で2つのウェイバインディングを取り除いています。 – FlavorScape

関連する問題