我对我的问题做了一个傻瓜... 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...
最佳答案
测试模块没有看到 MenuDirective
因为你忘了从假模块导出它:
@NgModule({
declarations: [
MenuComponent,
MenuDirective,
],
exports: [MenuDirective], <== add this
entryComponents: [MenuComponent]
})
class FakeEntryComponents {}
而且你似乎想查询 MenuComponent
menuElement = fixture.debugElement.query(By.directive(MenuComponent))
另见
关于使用 viewchild 和指令进行 Angular 组件测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45531089/