当前位置: 代码迷 >> JavaScript >> 如何测试角度指令范围
  详细解决方案

如何测试角度指令范围

热度:39   发布时间:2023-06-05 11:40:21.0

我遇到了单元测试的问题

我有类似的东西

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 而是使用具有toys属性的已设置scope变量。

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

  相关解决方案