0
votes

I have an Angular project that whatever spec file I created to test any component is failing due Error: Illegal state: Could not load the summary for directive ...

For example, I created a component that contains some Material design tags, and belongs to a module called PagesModule, the component does not do anything:

pages.module.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../_shared/shared.module';
import { NotFoundComponent } from './error/not-found/not-found.component';

@NgModule({
    declarations: [NotFoundComponent],
    imports: [SharedModule, RouterModule],
    exports: [],
    providers: []
})
export class PagesModule {}

not-found.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { MatCardModule } from '@angular/material';
import { NotFoundComponent } from './not-found.component';

describe('NotFoundComponent', () => {
    let component: NotFoundComponent;
    let fixture: ComponentFixture<NotFoundComponent>;

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [SharedModule],
            declarations: [NotFoundComponent]
        }).compileComponents();
    }));

    beforeEach(() => {
        fixture = TestBed.createComponent(NotFoundComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeDefined();
    });
});

Additional information: My SharedModule is already exporting all necessary material modules.

1
Use NO_ERRORS_SCHEMA in the module of your spec file.Anand Bhushan

1 Answers

1
votes

Your NotFoundComponent may contain nested components or directives, whose templates may contain more components. There are basically two techniques to deal with this in your tests (see. Nested component tests).

  1. create and declare stub versions of the components and directives
  2. add NO_ERRORS_SCHEMA to the TestBed.schemas metadata.

When opting for the first solutions, your test could look something like this.

@Component({selector: 'app-nested', template: ''})
class NestedStubComponent {}

describe('NotFoundComponent', () => {
    ...

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            imports: [SharedModule],
            declarations: [NotFoundComponent]
        }).compileComponents();
    }));

When opting for the second solution, TestBed.configureTestingModule would have to be changed as follows.

TestBed.configureTestingModule({
    imports: [SharedModule],
    declarations: [NotFoundComponent],
    schemas: [NO_ERRORS_SCHEMA]
}).compileComponents();