How to solve error "Can't bind to 'ngIf' since it isn't a known property of 'span'"

978 Views Asked by At

I am developing unit tests in an Angular 12 app with the help of Jest testing framework. Now there is a console error "Can't bind to 'ngIf' since it isn't a known property of 'span'" within child component after test run.

By the way, the data which is checked in *ngIf condition is received via @Input()

Here is the HTML:

<span class="month-name" *ngIf="name && year">
    {{ name.toUpperCase() }}
    <span class="year">{{ year }}</span>
</span>

This is the TypeScript code:

export class MonthNameComponent implements OnInit {
  @Input() name: string = '';
  @Input() year: string = '';

  constructor() {}

  ngOnInit(): void {}
}

Finally, this is what the test file looks like:

    describe('MonthNameComponent', () => {
      let component: MonthNameComponent;
      let fixture: ComponentFixture<MonthNameComponent>;
    
      beforeEach(async () => {
         await TestBed.configureTestingModule({
         imports: [CommonModule],
         declarations: [MonthNameComponent],
         providers: [],
         schemas: [NO_ERRORS_SCHEMA]
       }).compileComponents();

        fixture = TestBed.createComponent(MonthNameComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
      });
    
      it('should create', () => {
        expect(component).toBeTruthy();
      });
    });

NOTE:

I have read multiple recommendations regarding this error and did following things:

  1. Checked existence of CommonModule for a lazy loaded module that contains this component
  2. Imported CommonModuleinto the .spec file of component
  3. Included the component in TestBed providers
  4. Re-run application (several times).
  5. Added NO_ERRORS_SCHEMA into schema array

However, the error message still appears.

1

There are 1 best solutions below

0
On

I fixed it by adding the child component in declaration array of parent spec component, it should look like that :

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

  beforeEach(async () => {
     await TestBed.configureTestingModule({
     imports: [CommonModule],
     // add your child component here
     declarations: [ParentNameComponent, MonthNameComponent],
     providers: [],
   }).compileComponents();

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

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