使用 viewchild 和指令进行 Angular 组件测试

标签 angular testing

我对我的问题做了一个傻瓜... 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))

Plunker Example

另见

关于使用 viewchild 和指令进行 Angular 组件测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45531089/

相关文章:

testing - 复制较差的 Wi-Fi 进行测试

javascript - 如何使用 Protractor 处理具有相同中继器的两个表

testing - 如何在机器人框架中导入具有常用关键字的文件?

node.js - 如何从脚本命令访问 process.env 变量

angular - 如何延迟 Angular 2+ 中的输入验证

go - 如何在基准函数中使用 "testing.Benchmark"

unit-testing - WatiN - 要测试什么?

angular - ionic 可选 : error TS1086: An accessor cannot be declared in an ambient context

javascript - Angular 2 typescript 编译器错误

angular - 以 Angular 4 模板显示 map 内容