如何测试角度指令范围

时间:2015-07-30 23:02:29

标签: javascript angularjs unit-testing jasmine

我正在解决单元测试的问题

我有类似

的东西
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。任何人都可以帮我吗?非常感谢!

1 个答案:

答案 0 :(得分:2)

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

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

<强> Demo