如何测试 angular 指令范围

How to test angular directive scope

我运行单元测试有问题

我有类似的东西

describe('test controller', function () {
    var =$compile, scope, rootScope;

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

    describe('test', function() {
        beforeEach(function () {
            scope.toys = ['toy1', 'toy2'];            
        });
        it('should test directive' , function() {
            var element = $compile('<button type="button"  show-item>See all</button>')($rootScope);
            element.triggerHandler('click');
            $rootScope.$digest();
        });
    });
});

html

   <button type="button"  show-item>See all</button>

指令

angular.module('myApp').directive('showItem', 
function() {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, elem, attrs) {                
            elem.bind('click', function() {
                var l = scope.toys.length;
                //other codes
            });
     }
});

当我 运行 单元测试时,我得到 undefined' is not an object (evaluating 'scope.toys.length')

我不确定哪里出了问题,因为我已经在 beforeEach 函数中指定了 scope.toys。谁能帮我解决这个问题?非常感谢!

那是因为您正在使用 $rootScope 进行编译,其中没有 属性 toys。而是使用已经设置的 scope 变量,其中有 toys 属性.

  var element = $compile('<button type="button"  show-item>See all</button>')(scope);

Demo