Error message “Can’t bind to ‘ngIf’ since it isn’t a known property of ‘div'” solved
When testing a component in Angular you might receive the follwoting warning:
Can’t bind to ‘ngIf’ since it isn’t a known property of ‘div’
It might depend on you not declaring the component-under-test.
See this repo.
describe('AppComponent', () => { beforeEach(async () => { await TestBed.configureTestingModule({ imports: [ RouterTestingModule ], declarations: [ AppComponent ], }).compileComponents(); }); it('should create the app', () => { const fixture = TestBed.createComponent(AppComponent); const app = fixture.componentInstance; expect(app).toBeTruthy(); }); });
The code is slightly different than the boiler plate Angular/Jasmine test code but still visualises the issue.
The row
const fixture = TestBed.createComponent(AppComponent);
Creates a component that must be declared in
declarations: [ AppComponent ],
It took me an hour to find it due to code being convoluted.
If it saves you 5 minutes, it was worth writing this post.
Tags: angular, jasmine, test, testing, typescript
It’s likely that incorrect syntax or the lack of a dependant module is causing the problem. This is also caused by missing modules in lazy-loaded parent and child modules. To fix the problem, import BrowserModule in the parent module and CommonModule in the child module. The parent module always imports BrowserModule, while feature and child modules import CommonModule. Refer to this https://kodlogs.net/328/cant-bind-to-ngif-since-it-isnt-a-known-property-of-div
It’s likely that incorrect syntax or the lack of a dependant module is causing the problem. This is also caused by missing modules in lazy-loaded parent and child modules. To fix the problem, import BrowserModule in the parent module and CommonModule in the child module. The parent module always imports BrowserModule, while feature and child modules import CommonModule. Refer to this https://kodlogs.net/328/cant-bind-to-ngif-since-it-isnt-a-known-property-of-div