Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular test fails because Component is part of the declarations of 2 modules

Tags:

angular

I am creating some tests in Angular 4. I have a component that is using PrettyJsonCompont in order to show well formatted json to the user.

When I run ng test several of my component tests fail with the same message.

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.

Here is what my test looks like.

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();   }); }); 
like image 558
mattwallace Avatar asked Aug 18 '17 19:08

mattwallace


Video Answer


1 Answers

The problem is that configureTestingModule creates a new Angular module. And you declare the component PrettyJsonComponent in it. But this component is already declared in the PrettyJsonModule that you import. One component cannot be declared in two modules and that what the error reports.

To fix just remove PrettyJsonComponent from configureTestingModule declarations.

like image 106
Max Koretskyi Avatar answered Sep 28 '22 10:09

Max Koretskyi