Angular Jasmine单元测试:TypeError:this.sitesTable.renderRows不是函数



我在Angular/Jasmine/Karma中的简单单元测试中出现以下错误。

TypeError: this.sitesTable.renderRows is not a function

我在NgForm里面有一张垫子桌子。我想测试我重新设置Form和renderRows的方法,但它抛出了这个错误。它在正常的"非测试环境"中工作。

测试:

it('should reset Form when resetForm invoked', () => {
spyOn(component.studyForm, 'resetForm');
component.resetForm();
expect(component.studyForm.resetForm).toHaveBeenCalledTimes(1);
});

测试方法:

resetForm(){
this.studyForm.resetForm();
this.ngOnInit();
this.sitesTable.renderRows();
}

我可以请你们帮我,或者给我文章的链接,或者任何有帮助的东西吗?

感谢

我找到了解决方案,我认为它对有同样问题的人很有用。

解决方案:将MaterialModule和BrowserAnimationsModule添加到测试文件中的导入。

解决方案描述:

我阅读了关于TestBed的Angular文档https://angular.io/guide/testing.如果我理解正确的话,TestBed.configureTestingModule((创建一个完全分离的Module版本。因此,在我的案例中,我有两个模块:AppModule和TestBed(类似于AppModuleTest(

在这种情况下,应在两个模块中添加MaterialModule。还应导入BrowserAnimationsModule以启用MaterialModule。

如果有更有经验的人能纠正我或添加更多内容,我将非常感激。

尝试在测试中实例化一个新的MatTable,并设置为component.sitesTable。可能是ViewChild没有在测试中检索MatTable实例。这将是一个简单的解决方案。然后可以在renderRows方法上进行spyOn。

祝你好运!

最新更新