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

时间:2015-09-14 12:42:11

标签: javascript angularjs unit-testing jasmine

我有一个指令,它为元素添加了一个点击处理程序:

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的属性,并且通过在指令中添加控制台日志,我可以在单击绑定元素之前和之后看到属性,并且它们具有预期值(例如,属性以{{开头) 1}}并在您切换到false后点击切换元素。

然而,测试总是失败并且'预期错误等于真'。我认为这与true方法有关,因为在运行测试时,范围内似乎没有show属性。

我有的其他测试(即使在相同的spec文件中),不使用该指令可以看到范围上的属性就好了。

我做错了什么?

1 个答案:

答案 0 :(得分:3)

您的测试中有一些事情需要改变:

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

2 - 该指令不应编译为rootScope,而应编入范围

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

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