我正在 Angular 4 中创建一些测试。我有一个使用 PrettyJsonCompont 的组件,以便向用户显示格式良好的 json。
当我运行 ng test 时,我的几个组件测试失败并显示相同的消息。
Failed: Type PrettyJsonComponent is part of the declarations of 2 modules: PrettyJsonModule and DynamicTestModule! Please consider moving PrettyJsonComponent to a higher module that imports PrettyJsonModule and DynamicTestModule. You can also create a new NgModule that exports and includes PrettyJsonComponent then import that NgModule in PrettyJsonModule and DynamicTestModule.
这是我的测试结果。
import {async, ComponentFixture, TestBed} from '@angular/core/testing';
import {ContentItemModalComponent} from './content-item-modal.component';
import {DialogService} from 'ng2-bootstrap-modal';
import {ContentItemService} from '../services/content-item.service';
import {FormsModule, ReactiveFormsModule} from '@angular/forms';
import {FroalaEditorModule, FroalaViewModule} from 'angular-froala-wysiwyg';
import {HttpModule} from '@angular/http';
import {MainModel} from '../models/main-model';
import {PrettyJsonComponent, PrettyJsonModule} from 'angular2-prettyjson';
describe('ContentItemModalComponent', () => {
let component: ContentItemModalComponent;
let fixture: ComponentFixture<ContentItemModalComponent>;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
ReactiveFormsModule,
FormsModule,
FroalaEditorModule.forRoot(),
FroalaViewModule.forRoot(),
HttpModule,
PrettyJsonModule
],
declarations: [ContentItemModalComponent, PrettyJsonComponent],
providers: [
DialogService,
ContentItemService,
MainModel
],
})
.compileComponents();
}));
beforeEach(() => {
fixture = TestBed.createComponent(ContentItemModalComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});
it('should be created', () => {
expect(component).toBeTruthy();
});
});
最佳答案
问题是 configureTestingModule
创建了一个新的 Angular 模块。然后在其中声明组件 PrettyJsonComponent
。但是这个组件已经在您导入的 PrettyJsonModule
中声明了。一个组件不能在两个模块中声明,这是错误报告的内容。
要修复,只需从 configureTestingModule
声明中删除 PrettyJsonComponent
。
关于 Angular Testing 失败,因为组件是 2 个模块声明的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45764202/