单元测试 Angular 指令点击处理程序

Unit testing Angular directive click handler

我有一个向元素添加点击处理程序的指令:

module.directive('toggleSection', ['$timeout', function ($timeout) {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            element.bind('click', function (event) {
                scope.$apply(function () {
                    var scopeProp = 'show' + attrs.toggleSection;

                    event.preventDefault();
                    event.stopPropagation();

                    scope[scopeProp] = !scope[scopeProp];

                    return false;
                });

            });
        }
    };
}]);

单击该元素时,它会在范围内切换另一个 属性,另一个元素使用 ng-show 绑定到该范围。它在应用程序中正常运行。

我为指令添加了以下测试:

(function () {
    'use strict';

    // get the app module from Angular
    beforeEach(module('app'));

    describe('myCtrl', function () {

        var $scope, $rootScope;

        beforeEach(inject(function ($controller, _$rootScope_) {
            $scope = {};
            $controller('myCtrl', { $scope: $scope });
            $rootScope = _$rootScope_;
        }));

        describe('the toggleSection directive', function () {

            var testElement;

            beforeEach(function () {
                testElement = $compile('<a toggle-section="Test" href="#">Collapse section</a>')($rootScope);
                $rootScope.$digest();
            });

            it('inverts the value of the specified scope property', function () {
                $scope.showTest = false;
                testElement.click();

                expect($scope.showTest).toEqual(true);
            });

        });
    });

在实际代码中有像 $scope.showSection1 = false 这样的属性,通过在指令中添加控制台日志,我可以看到单击绑定元素之前和之后的属性,并且它们具有预期值(例如 属性 以 false 开始,单击切换元素后,一旦它变为 true).

但是,测试总是失败并显示 'Expected false to equal true'。我认为这与 $apply 方法有关,因为当我 运行 测试时,显示属性的 none 似乎存在于范围内。

我进行的其他测试(即使在同一个规范文件中)不使用该指令可以很好地查看作用域上的属性。

我做错了什么?

您的测试中有几项需要更改:

1 - 范围创建应从 $scope = {} 更改为 $scope = $rootScope.$new();

2 - 该指令不应编译到 rootScope 中,而是编译到范围中

3 - 该指令应首先通过 angularjs.element 创建,然后编译:

element = angular.element('<my-directive/>');
compile(element)(scope);
scope.$digest();