Angular Testing 失败,因为组件是 2 个模块声明的一部分

标签 angular

我正在 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/

相关文章:

Angular2 CLI : why bundle size of "--prod" smaller than "--prod --aot"?

Angular 2 : Cannot set property 'location' of null

angular - 找不到名称 'google' Angular 8

angular - Angular 的 canLoad 和 canActivate 之间的区别?

html - Angular2 - 将 CSS 类添加到选定元素

Angular 4 : Get all properties that are decorated with @Input

angular - 动画 Material 图标转换 : Hamburger to X

javascript - 在 Ionic 2/Angular 2 beta 10 中访问窗口对象

html - 如何将 div 的动态列表排列成 2 列

angular - 如何使 Angular 模块忽略核心模块中添加的http拦截器