单元测试angularjs指令,带观察元件高度

单元测试angularjs指令,带观察元件高度,angularjs,angularjs-directive,jasmine,angularjs-compile,angularjs-watch,Angularjs,Angularjs Directive,Jasmine,Angularjs Compile,Angularjs Watch,我计划使用jasmine对angular指令进行单元测试。我的指令是这样的 angular.module('xyz.directive').directive('sizeListener', function ($scope) { return { link: function(scope, element, attrs) { scope.$watch( function() { return Math.max(el

我计划使用jasmine对angular指令进行单元测试。我的指令是这样的

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();
    });

});
});
description('Size listener指令',函数(){
var$rootScope,$compile,$scope,element;
beforeach(注入(函数($rootScope,$compile){
$rootScope=\u$rootScope;
$compile=\$compile;
$scope=$rootScope.$new();
元素=角度。元素('

'); $compile(元素)($scope); $scope.$digest(); })); 描述(“尺寸变化”,功能(){ 它(“应该调用sizeChanged方法”,函数(){ 元素[0]。远视=1; $compile(元素)($scope); $scope.$digest(); $scope.$apply(函数(){}); expect($scope.sizeChanged).toHaveBeenCalled(); }); }); });

代码运行良好。但是单元测试失败了。调用了watch函数,但元素[0]。watch中的offsetHeight始终返回0。我们如何更新元素,以便手表可以观察到新的高度。有没有一种方法可以测试这个,因为我们这里没有真正的DOM。请指导我在单元测试中需要做的更改

若要获取元素的
离视
,它需要位于页面上,因此您需要将其附加到文档:

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
。 有关更多信息:

这篇文章帮助我找到了答案: