我的项目中有属性指令和结构指令。我可以通过创建测试组件并在其模板中使用属性指令来测试属性指令。
@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
的约束。 , 而不是 DebugNode
.这是一个很小的差异,但可以解释为什么找不到它。
要找到实例,您必须以不同的方式查询:
# Angular 8.1 or below
debugElement.queryAllNodes(debugNode => debugNode.providerTokens.includes(MyStrucDirective))[0];
# Angular 8.2
debugElement.queryAllNodes(By.directive(MyStrucDirective))[0];
关于angular - 是否可以像我们在 angular 2 中测试属性指令那样对结构指令进行单元测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51839072/