【问题标题】:Angular component test with viewchild and directive带有 viewchild 和指令的 Angular 组件测试
【发布时间】:2018-01-13 19:49:22
【问题描述】:

我对我的问题做了一个笨拙的人...https://embed.plnkr.co/UparfJDomOECGJfWSbqA/ 简而言之:我无法测试我的组件,它似乎在container.component.spec.ts:43 中失败 - 但没有fixture.detectChanges(),ngAfterViewInit 将不会启动。我看不出我做错了什么。

我想将组件动态加载到具有指令属性的 ng-template 中,并且该解决方案确实有效,但我无法为其编写工作测试。 因为我对单元测试还很陌生……那是我应该测试的吗 - 我认为是的。 (是的,我阅读了 angular.io 测试指南和其他一些 ;-)) 错误是 TypeError: Cannot read property 'viewContainerRef' of undefined,这似乎表明 @ViewChild 没有 ViewChild...

【问题讨论】:

    标签: angular testing


    【解决方案1】:

    测试模块看不到MenuDirective,因为您忘记从假模块中导出它:

    @NgModule({
        declarations: [
            MenuComponent,
            MenuDirective,
        ],
        exports: [MenuDirective], <== add this
        entryComponents: [MenuComponent]
    })
    class FakeEntryComponents {}
    

    看来你想查询 MenuComponent

    menuElement = fixture.debugElement.query(By.directive(MenuComponent))
    

    Plunker Example

    另见

    【讨论】:

    • 先生,您是英雄。非常感谢
    猜你喜欢
    • 2019-06-25
    • 2021-02-12
    • 2015-02-26
    • 2020-05-09
    • 2018-10-07
    • 2019-12-24
    • 2019-01-02
    • 2020-08-05
    • 1970-01-01
    相关资源
    最近更新 更多