Search code examples
javascriptangularunit-testingjasmineangular-test

Get routerLink properties from HTML in Angular unit test


I have following HTML property:

   <ul>   
      <li class="nav-item" routerLinkActive="active">
        <a class="nav-link" [routerLink]="['/home']">Home</a>
      </li>
    </ul>

I want now to get the href as a value in the unit test. So far I have in my test-case:

  it('should navigate have login navigation', () => {
     const debugElements = fixture.debugElement.queryAll(By.css('a.nav-link'));
     debugElements.forEach(x  => console.log(x.properties['href']));
  });
});

But that is every time undefined. How do I fetch the href from the rounterLink directive? Incidentally, I don't need to do fixture.detectChanges(); Since I don't use lifecycle-hooks in this particular comp.


Solution

  • You actually have to run fixture.detectChanges(). This is not limited to lifecycle hooks but concerns change detection in general (so pretty much any magic that Angular does).

    I've created a Stackblitz demonstrating that the test is failing without detectChanges and running with it.