是否可以像我们在角度2中测试属性指令的方式对结构指令进行单元测试

use*_*ser 5 angular-directive angular

我的项目中同时具有属性和结构指令。我可以通过创建测试组件并在模板中使用attribute指令来测试attribute指令。

@Component({
    template: `<input [myAttrDir]="{prop1: val1, prop2: val2}"/>`
})
export class TestComponent {
}

@Directive({
    selector: '[myAttrDir]'
})
export class MyAttrDirective {
    @Input('myAttrDir') testProp;
}
Run Code Online (Sandbox Code Playgroud)

测试模块如下所示:

TestBed.configureTestingModule({
    declarations: [MyAttrDirective, TestComponent]
})
Run Code Online (Sandbox Code Playgroud)

我这样掌握指令:

fixture = TestBed.createComponent(TestComponent)
directive = fixture.debugElement.query(By.directive(MyAttrDirective))
Run Code Online (Sandbox Code Playgroud)

我能够获得属性指令的实例。但是,当我尝试以相同的方式测试结构化指令时,会得到指令的空值。我也检查了官方文档,仅发现attribute指令的单元测试。在任何地方都没有给出结构指令测试方法。

@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))
Run Code Online (Sandbox Code Playgroud)

是否可以通过任何方式测试结构指令?

Dir*_*ijk 18

我有同样的问题,但我想出了为什么debugElement.query(By.directive(MyStrucDirective))不适用于结构指令。

结构指令应用于模板 ( <ng-template>) 而不是元素。这意味着,它们不绑定到 any 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];
Run Code Online (Sandbox Code Playgroud)