带有导入模块的单元测试angular2组件 [英] Unit Testing angular2 component with imported module
问题描述
我试图在使用angular-material2的组件上编写测试,但是当我将其添加到testModule声明中时,我得到了:
I am trying to write a test on a component which uses angular-material2, but when I add it to my testModule declarations I get:
Error: Template parse errors:
'md-card-title' is not a known element:
1. If 'md-card-title' is an Angular component, then verify that it is part of this module.
2. If 'md-card-title' is a Web Component then add "CUSTOM_ELEMENTS_SCHEMA" to the '@NgModule.schemas' of this component to suppress this message.
在声明中添加MaterialModule会引发`错误:模块声明了意外的模块'MaterialModule'
Adding MaterialModule to the declarations throws `Error: Unexpected module 'MaterialModule' declared by the module
config/spec-bundle.js中的DynamicTestModule'(第24994行)
DynamicTestModule' in config/spec-bundle.js (line 24994)
这是我的规格文件的外观:
This is what my spec file looks like:
beforeEach(() => TestBed.configureTestingModule({
declarations: [],
providers: [
{ provide: DataService, useValue: mockDataService },
{ provide: ActivatedRoute, useClass: MockActivatedRoute },
{ provide: Router, useValue: mockRouter },
CellViewComponent
]
}));
在声明数组中添加CellViewComponent
会引发错误.
adding CellViewComponent
to the declarations array causes the error to throw.
推荐答案
使用TestBed.configureTestingModule
时,将为测试环境从头开始创建模块 .因此,在实际应用程序中,要使CellViewComponent
正常运行所需要的一切,还需要在测试模块中进行配置.
When you use the TestBed.configureTestingModule
, you're create a module from scratch for the test environment. So what ever you would need in the real application for the CellViewComponent
to work, you also need to configure it in the testing module.
在您的情况下,您缺少物料卡组件.在应用程序中,您可能将MaterialModule
或MdCardModule
导入到AppModule
中.所以您需要在测试模块中做同样的事情
In your case, you're missing the Material card component. In the app you probably either imported the MaterialModule
or the MdCardModule
into your AppModule
. So you need to do the same in the testing module
beforeEach(() => TestBed.configureTestingModule({
imports: [ MaterialModule /* or MdCardModule */ ],
declarations: [ CellViewComponent ],
providers: [
{ provide: DataService, useValue: mockDataService },
{ provide: ActivatedRoute, useClass: MockActivatedRoute },
{ provide: Router, useValue: mockRouter },
]
}));
这篇关于带有导入模块的单元测试angular2组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!