I want to test if a div is visible in my Angular unit test. The portion of the HTML code I wanted to test is:
<div *ngIf="hasId | async">
<div class="container">
...some more html code....
</div>
</div>
Here hasId is a Promise boolean variable. It is initiated in the ngOnInit() like below:
this.securityService.Id$.subscribe({
next: (id: string | undefined) => {
this.Id= id ? id : this.securityService.EmptyGuid;
this.hasId = Promise.resolve(true);
},
});
in my unit test spec file I have written following code:
it('Should container visible', () => {
expect(fixture.debugElement.query(By.css('.container')).nativeElement).toBeTruthy();
});
the above code throwing null exception as TypeError: Cannot read properties of null (reading 'nativeElement')
which I believe the element is not loaded yet as it is inside a async div. So I change my code in following way:
it('Should container visible', () => {
fixture.whenStable().then(() => {
expect(fixture.debugElement.query(By.css('.container')).nativeElement).toBeTruthy();
});
});
this time the test getting passed but in the console i can still see there are warning and error, which is basically the same null exception in NativeElement. I am sharing the screenshot of my VS code console here:
I believe I need to access this container div in different way, but I didn't find out a way still. How can I achieve this?