1

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:

enter image description 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?

  • maybe mock the input as being true all the time for that particular test? Or you could use a specific test id. I saw this tip when I was researching testing myself but never used it – Cristian Cutitei Jun 17 '22 at 08:38
  • could you please give me some sample code for the tip you said. – Fazla Elahi Md Jubayer Jun 17 '22 at 08:47
  • a similar question: https://stackoverflow.com/questions/60487439/cannot-wait-until-dom-rendering-has-finished-in-angular-jasmine-unit-test – CCBet Jun 17 '22 at 10:07

0 Answers0