我遇到了单元测试的问题
我有类似的东西
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