menu

Questions & Answers

Angular Testing RouterLink | Jasmine Test Infinite Loop

I'm creating a test for the Navbar component. When I test the button click on the logout key, Jasmine's test starts an infinite loop.

describe('NavbarComponent', () => {
  let component: NavbarComponent;
  let fixture: ComponentFixture<NavbarComponent>;
  let router: Router;


  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [ RouterTestingModule.withRoutes(
        [{path: 'user', component: UserComponent},
        {path: 'posts', component: PostsComponent},
        {path: '', component: SigninComponent}
      ]
      ), HttpClientModule],
      schemas: [NO_ERRORS_SCHEMA],
      declarations: [NavbarComponent],
    });
    fixture = TestBed.createComponent(NavbarComponent);
    component = fixture.componentInstance;
    router = TestBed.get(Router); 
  });

Below is my test, I have already created other similar tests and they have not given me any problems. Could it be related to the logout page? Any tip will be appreciated!

fit('navigates to / when the "logout" button is clicked', fakeAsync(() => {
    const navSpy = spyOn(router, 'navigateByUrl');
    const buttons = fixture.debugElement.query(By.css('#logout'));
    expect(buttons).toBeTruthy();
    (buttons.nativeElement as HTMLButtonElement).click();
    fixture.detectChanges();
    tick();
    expect(navSpy).toHaveBeenCalledWith(
      router.createUrlTree(['/']), 
      jasmine.anything()
    );
  }));
Answers(1) :

After a few tries, I managed to find the solution. It was enough to create a method in the component.ts that redirected to the Login page. In this way, the test passed without any problems. Of course, from the html I removed the router link that redirected to the login page and replaced it with a call to the method I built in the ts file.