问题描述
我遇到了单元测试的问题
我有类似的东西
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楼
PSL
2
已采纳
2015-07-30 23:31:00
这是因为您正在使用$rootScope
进行编译,而其中没有属性toys
。
而是使用具有toys
属性的已设置scope
变量。
var element = $compile('<button type="button" show-item>See all</button>')(scope);