Angularjs 测试子指令与父指令的超越指令交互
我想测试子指令和父指令之间的交互: 我的例子是:Angularjs 测试子指令与父指令的超越指令交互,angularjs,angularjs-directive,angular-test,Angularjs,Angularjs Directive,Angular Test,我想测试子指令和父指令之间的交互: 我的例子是: app.directive('foo', function() { return { restrict: 'AE', template: '<div><div ng-transclude></div></div>', transclude: true, controller: function($scope) { this.add = functio
app.directive('foo', function() {
return {
restrict: 'AE',
template: '<div><div ng-transclude></div></div>',
transclude: true,
controller: function($scope) {
this.add = function(x, y) {
return x + y;
}
}
};
});
app.directive('bar', function() {
return {
restrict: 'AE',
require: '^foo',
template: '<div></div>',
replace: true,
link: function(scope, element, attrs, foo) {
console.log('link directive bar')
scope.callFoo = function(x, y) {
scope.sum = foo.add(x, y);
}
}
};
});
app.directive('foo',function(){
返回{
限制:“AE”,
模板:“”,
是的,
控制器:功能($scope){
this.add=函数(x,y){
返回x+y;
}
}
};
});
应用指令('bar',函数(){
返回{
限制:“AE”,
要求:“^foo”,
模板:“”,
替换:正确,
链接:函数(范围、元素、属性、foo){
console.log('link directive bar')
scope.callFoo=函数(x,y){
scope.sum=foo.add(x,y);
}
}
};
});
我想测试boo和test之间的交互,我不想模拟child指令(boo),这是我的测试:
it('ensures callFoo does whatever it is supposed to', function() {
// Arrange
var element = $compile('<div foo><bar></bar></div>')($scope);
var ele = element.find('bar')
var barScope = element.find('bar').scope();
console.log('parent element :',element)
console.log('child element :',ele)
// Act Undefined :(
barScope.callFoo(1, 2);
// Assert
expect(barScope.sum).toBe(3);
});
it('确保callFoo执行它应该执行的任何操作',function(){
//安排
var元素=$compile(“”)($scope);
var ele=element.find('bar')
var barScope=element.find('bar').scope();
console.log('父元素:',元素)
log('子元素:',ele)
//未定义的行为:(
barScope.callFoo(1,2);
//断言
expect(barScope.sum).toBe(3);
});
完整示例:
您的指令已经编译,并且由于您在
bar
指令上有replace:true
,因此在DOM中再也找不到bar
。您可以通过查看element.html()
看到这一点,在您的案例中会显示类似的内容:
<div><div ng-transclude=""><div class="ng-scope"></div></div></div>
你的应用程序中是否加载了jQuery?如果是这样,你也可以在测试中加载它,然后向栏
元素添加更多信息,如:
var element = $compile('<div foo><bar id="bar"></bar></div>')($scope);
是的var ele=angular.element(element.find('div')[2])适合我:)谢谢Frank
var element = $compile('<div foo><bar id="bar"></bar></div>')($scope);
var barScope = element.find('#bar').scope();