2

ジャスミンを使用して角度指令をユニットテストする予定です。私のディレクティブは、このユニットの高さでのウォッチ付きanglejs指令

angular.module('xyz.directive').directive('sizeListener', function ($scope) { 
return { 
    link: function(scope, element, attrs) { 
     scope.$watch(
      function() { 
       return Math.max(element[0].offsetHeight, element[0].scrollHeight); 
      }, 
      function(newValue, oldValue) { 
       $scope.sizeChanged(newValue); 
      }, 
      true 
     ); 
    } 
}; 
}); 

のように見えます

describe('Size listener directive', function() { 

var $rootScope, $compile, $scope, element; 

beforeEach(inject(function(_$rootScope_, _$compile_) { 
    $rootScope = _$rootScope_; 
    $compile = _$compile_; 
    $scope = $rootScope.$new(); 

    element = angular.element('<span size-listener><p></p></span>'); 
    $compile(element)($scope); 
    $scope.$digest(); 
})); 

describe("Change in size", function() { 

    it("should call sizeChanged method", function() { 

     element[0].offsetHeight = 1; 
     $compile(element)($scope); 
     $scope.$digest(); 
     $scope.$apply(function() {}); 

     expect($scope.sizeChanged).toHaveBeenCalled(); 
    }); 

}); 
}); 

コードが正常に動作しますが、次のように私のユニットテストケースがあります。しかし、ユニットテストは失敗します。 watch関数は呼び出されますが、watch [0]の.offsetHeightは常に0を返します。時計が新しい高さを観測できるように要素を更新するにはどうすればいいですか?実際にDOMを持っていないので、これをテストする方法もありますか?単体テストで行う必要がある変更について私を案内してください。

答えて

1

要素のoffsetHeightを取得するには、ドキュメントに添付する必要があるので、それは、ページ上にある必要があります。

it("should call sizeChanged method", function() { 
    element[0].style.height = '10px'; 

    $compile(element)($scope); 
    angular.element($document[0].body).append(element); 
    $scope.$apply(); 

    expect($scope.sizeChanged).toHaveBeenCalled(); 
}); 

ところでは、offsetHeightが読み取り専用のプロパティをのでstyle.heightを使用。詳細情報については :https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetHeight

この投稿は、私は答えを見つける助け:Set element height in PhantomJS