【问题标题】:Unit Test angularjs directive with watch on element height单元测试 angularjs 指令,监视元素高度
【发布时间】:2016-12-07 03:17:24
【问题描述】:

我计划使用 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();
    });

});
});

代码运行良好。但是单元测试失败了。 watch 函数被调用,但是 watch 中的 element[0].offsetHeight 总是返回 0。我们如何更新元素以便 watch 可以观察到新的高度。有没有办法甚至测试这个,因为我们这里并没有真正的 DOM。请指导我需要通过单元测试完成的更改。

【问题讨论】:

    标签: angularjs angularjs-directive jasmine angularjs-compile angularjs-watch


    【解决方案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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-03-09
      • 2014-08-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-23
      • 2015-09-15
      • 1970-01-01
      相关资源
      最近更新 更多