angular - 是否可以像我们在 angular 2 中测试属性指令那样对结构指令进行单元测试

标签 angular angular-directive

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

@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/

相关文章:

javascript - Angular Directives - 如何将属性设置为innerHML

javascript - 将指令添加到 Angular-xeditable 输入字段

angular - *ngIf 不对 bool 值变化使用react

javascript - 创建列表并使用 Angular Directive(指令)进行渲染

javascript - 如何将 Mat-Select 值传递到 API 调用中的 header

javascript - Angular2 中的 WebSocket

css - Angular cdk拖放: keep element style after drop into other container

java - 从客户端浏览器 (REST) 上的服务器返回一个 zip(或任何文件)

Angular2 路由

angular - 如何在 Angular 5 中的指令上使用 exportAs 以在模板中获取其引用?