是否可以像我们在angular 2中测试属性指令那样对结构指令进行单元测试 [英] Is it possible to unit test a structural directive the way we test an attribute directive in angular 2
问题描述
我在项目中同时具有属性和结构指令.我可以通过创建测试组件并在其模板中使用属性指令来测试属性指令.
I have both attribute and structural directives in my project. I am able to test the attribute directive by creating a test component and using the attribute directive in it's template.
@Component({
template: `<input [myAttrDir]="{prop1: val1, prop2: val2}"/>`
})
export class TestComponent {
}
@Directive({
selector: '[myAttrDir]'
})
export class MyAttrDirective {
@Input('myAttrDir') testProp;
}
测试模块如下:
TestBed.configureTestingModule({
declarations: [MyAttrDirective, TestComponent]
})
我以这种方式掌握指令:
I get hold of directive this way:
fixture = TestBed.createComponent(TestComponent)
directive = fixture.debugElement.query(By.directive(MyAttrDirective))
我能够获取attribute指令的实例. 但是,当我尝试以相同的方式测试结构化指令时,会得到指令的空值. 我也检查了官方文档,仅发现了attribute指令的单元测试.没有任何地方提供结构指令测试方法.
I am able to get the instance of attribute directive. However when I try this same way to test structural directive, I get null value of directive. I have checked out official documentation as well and only found the unit testing of attribute directive. The structural directive testing methodology is not given anywhere.
@Component({
template: `<input *myStrucDir="{prop1: val1, prop2: val2}"/>`
})
export class TestComponent {
}
@Directive({
selector: '[myStrucDir]'
})
export class MyStrucDirective {
@Input set myStrucDir(data);
constructor(
private templateRef: TemplateRef<any>,
private vcr: ViewContainerRef,
private cfr: ComponentFactoryResolver,
private el: ElementRef) {
}
}
TestBed.configureTestingModule({
declarations: [MyStrucDirective, TestComponent]
})
fixture = TestBed.createComponent(TestComponent)
directive = fixture.debugElement.query(By.directive(MyStrucDirective))
是否可以以任何方式测试结构指令?
Is it possible to test structural directive in any way?
推荐答案
我遇到了同样的问题,但是我弄清楚了为什么debugElement.query(By.directive(MyStrucDirective))
不适用于结构化指令.
I had the same issue, but I figured out why debugElement.query(By.directive(MyStrucDirective))
does NOT work for structural directives.
结构指令应用于模板(<ng-template>
)而不是元素.这意味着它们不绑定到任何DebugElement
,而是绑定到DebugNode
.差异很小,但是可以解释为什么找不到它.
Structural directives are applied to templates (<ng-template>
) instead of elements. This means, that they are not bound to any DebugElement
, but rather to a DebugNode
. That is a small difference, but explains why it is not found.
要查找实例,您必须进行不同的查询:
To find the instance, you have to query differently:
# Angular 8.1 or below
debugElement.queryAllNodes(debugNode => debugNode.providerTokens.includes(MyStrucDirective))[0];
# Angular 8.2
debugElement.queryAllNodes(By.directive(MyStrucDirective))[0];
这篇关于是否可以像我们在angular 2中测试属性指令那样对结构指令进行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!