angular - 是否可以像我们在 Angular 2 中测试属性指令一样对结构指令进行单元测试
问题描述
我的项目中有属性和结构指令。我可以通过创建测试组件并在其模板中使用属性指令来测试属性指令。
@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]
})
我以这种方式掌握指令:
fixture = TestBed.createComponent(TestComponent)
directive = fixture.debugElement.query(By.directive(MyAttrDirective))
我能够获得属性指令的实例。但是,当我尝试以相同的方式测试结构指令时,我得到指令的空值。我也检查了官方文档,只发现了属性指令的单元测试。结构指令测试方法在任何地方都没有给出。
@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))
是否可以以任何方式测试结构指令?
解决方案
我有同样的问题,但我想通了为什么debugElement.query(By.directive(MyStrucDirective))
不适用于结构指令。
结构指令应用于模板 ( <ng-template>
) 而不是元素。这意味着,它们不绑定到任何DebugElement
,而是绑定到 a DebugNode
。这是一个很小的差异,但解释了为什么找不到它。
要查找实例,您必须以不同的方式查询:
# Angular 8.1 or below
debugElement.queryAllNodes(debugNode => debugNode.providerTokens.includes(MyStrucDirective))[0];
# Angular 8.2
debugElement.queryAllNodes(By.directive(MyStrucDirective))[0];