Angular Unit Test shows error warnings of kind NG0304 "component is not a known element" even...

Discussão em 'Angular' iniciado por devledgers1357, Março 28, 2025.

  1. I am writing unit tests for an Angular component that uses multiple child components which are used with @ViewChild({}) in the following way:

    Template:

    ...
    <app-app-form></app-app-form>
    <app-terms-form></app-terms-form>
    ...


    Model:

    ...
    @ViewChild(AppFormComponent, {static: true}) protected appForm: AppFormComponent;
    @ViewChild(TermsFormComponent, {static: true}) protected termsForm: TermsFormComponent;
    ...


    In total I use six such components. For testing purposes I declared component stubs in this way:

    @Component({
    selector: 'app-terms-form',
    template: '',
    providers: [
    { provide: TermsFormComponent, useClass: TermsFormStubComponent }
    ]
    })
    class TermsFormStubComponent implements Partial<IFormComp<any>> {
    ...
    }


    When I run my tests I get error warning messages for all used child components although I declared them in the TestBed:

    ERROR: 'NG0304: 'app-terms-form' is not a known element (used in the 'CreateLicenseComponent' component template):
    1. If 'app-terms-form' is an Angular component, then verify that it is a part of an @NgModule where this component is declared.


    I want my tests to not display any error warnings for things that I deem already fixed but I can not figure out how to stop it. The TestBed is configured with all the necessary components.

    beforeEach(async () => {
    ...
    await TestBed.configureTestingModule({
    imports: [ ... ],
    schemas: [ CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA ], // doesn't resolve the error warnings NG0304
    declarations: [
    CreateLicenseComponent,
    OrderFormStubComponent,
    DeviceFormStubComponent,
    AppFormStubComponent,
    TermsFormStubComponent,
    DnFormStubComponent,
    ExpiresFormStubComponent
    ],
    providers: [ ... ]
    })
    .compileComponents();

    fixture = TestBed.createComponent(CreateLicenseComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    });


    As you can see I already added CUSTOM_ELEMENTS_SCHEMA and NO_ERRORS_SCHEMA, also tried each individually. But it doesn't work. And I should not have to add them in the first place because all needed elements are in the "declarations" array. I still get the error warnings for all six child components

    My tests run all successfully and through debugging I already confirmed that the component stubs are available. I could just ignore these error warnings but they are nevertheless annoying in particular because I am going to add more components like the showcased one. Does anyone have an idea how to cleanly solve this problem?

    Continue reading...

Compartilhe esta Página