gpt4 book ai didi

javascript - 如何测试 Angular Directive(指令)范围

转载 作者:行者123 更新时间:2023-11-30 16:42:30 25 4
gpt4 key购买 nike

我遇到了单元测试的问题

我有类似的东西

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

关于javascript - 如何测试 Angular Directive(指令)范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31735504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com