Tuesday, August 27, 2019

How do I unit test router.navigate(['/elsewhere']); in an Angular app?

You use the RouterTestingModule trick like so:

import { async, ComponentFixture, TestBed } from '@angular/core/testing';
import { RealComponent } from './real.component';
import { RouterTestingModule } from '@angular/router/testing';
import { StubComponent } from './stub.component';
describe('RealComponent', () => {
   let component: RealComponent;

   let fixture: ComponentFixture<RealComponent>;
   beforeEach(async(() => {
      TestBed.configureTestingModule({
         imports: [
            RouterTestingModule.withRoutes([
               {
                  path: 'elsewhere',
               component: StubComponent
               }
            ])
         ],
         declarations: [ RealComponent, StubComponent ]
      })
      .compileComponents();
   }));
   
   beforeEach(() => {
      fixture = TestBed.createComponent(RealComponent);
      component = fixture.componentInstance;
      fixture.detectChanges();
   });
   
   it('should create', () => {
      expect(component).toBeTruthy();
   });
});

 
 

StubComponent better be damn simple:

import { Component } from '@angular/core';
@Component({
   selector: 'stub',
   template: 'n/a'
})
export class StubComponent {
   constructor() {
   
   }
}

 
 

StubComponet likely needs to be ceremonially called out in one of your real modules too and not just the pseudo, on-the-fly "module" inside the test as if it is not mentioned somewhere as a reference it may break your production build.

No comments:

Post a Comment