NG0303: Can't bind to X since it isn't a known property of Y

47 Views Asked by At

Recently I upgraded my application to Angular 17

this error is only happening when I issue test command

ng test

Application build and execution works properly and it went to production everything is fine there, only in jasmine testing I am blocked, is anyone faced similar issue let me know the fix

Angular 17.0.0 code


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

  beforeEach(async () => {
    await TestBed.configureTestingModule({
      declarations: [ TestComponent ],
      imports: [
          CommonModule,
          BrowserModule,
          AppModule
      ]
    })
    .compileComponents();
  });

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

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

});

Error coming from

at reportUnknownPropertyError (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/fesm2022/core.mjs:9036:15)
2

There are 2 best solutions below

0
Dickens A S On BEST ANSWER

I fixed the issue by duplicating the module code app.module.ts to app.module.spec.ts

and introduce schema section with CUSTOM_ELEMENTS_SCHEMA, NO_ERRORS_SCHEMA as below

@NgModule({
    declarations: [
        AppComponent
    ],
    imports: [
        BrowserModule,
        AppRoutingModule,
        BrowserAnimationsModule,
        HttpClientXsrfModule,
        HttpClientModule
    ],
    bootstrap: [AppComponent],
    schemas: [
        CUSTOM_ELEMENTS_SCHEMA,
        NO_ERRORS_SCHEMA
    ]
})
export class AppModule {}

and use this new module in jasmine code

import { AppModule } from './app.module.spec';
describe('AppComponent', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      errorOnUnknownProperties: false,
      imports: [
        AppModule
      ]
    }).compileComponents();
  });
});
1
JSON Derulo On

You are getting an error because you are assigning type TestComponent to the component variable but in reality you are creating HeaderComponent. When assigning the fixture.componentInstance there is a type mismatch. To fix it, just create the right component:

fixture = TestBed.createComponent(TestComponent);

The currently accepted answer just ignores the issue and is not advisable. It will not make the component testable.