1

I am having issues writing a stub for router.navigate in angular 2. I currently have the below stub written. Which is what shows up in the angular docs.

@Injectable
export class RouterStub {
    navigate(commands: any[], extras?: NavigationExtras) { }

However, when I use this stub I get the following error.

TypeError: this.router.navigate is not a function 

And my usage of navigate is as follows.

let summaryLink = ['/summary', this.client.id, this.client.lastName];
this.router.navigate(summaryLink);

Any help would be appreciated.

Just an update... I was able to get this test working using a non TestBed method that I found referenced here. However, if anyone is able to figure out how I can get this test working with the TestBed method I would appreciate the help. Thank you

Community
  • 1
  • 1
TyAnthoney
  • 278
  • 4
  • 12

1 Answers1

1

You have to bootstrap your tests including the Router module. This is pretty the same like bootstrapping the application:

const IMPORTS: any[] = [
    BrowserModule,
    ...
    RouterModule.forRoot(routes)
];

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: IMPORTS,
    declarations: DECLARATIONS
    providers: PROVIDERS
  }).compileComponents();
}));

Then, you can obtain the reference to the router.

 beforeEach(() => {
  router = TestBed.get(Router);
  fixture = TestBed.createComponent(YourComponent);
  component = fixture.componentInstance;
  element = fixture.nativeElement;
});

Test for state (requires dependencies since the components get rendered and so on):

it('routes to the dummy component', fakeAsync(() => {
  tick(1000);
  fixture.detectChanges();

  router.navigate(['dummy']);

  tick(1000);
  fixture.detectChanges();

  expect(router.isActive('/dummy', true)).toBe(true);
}));

Test for communication (does not route; we just have to verify whether the navigation really happened):

it('routes to the dummy component', fakeAsync(() => {
  spyOn(router, 'navigate').and.callFake(() => {});
  tick(1000);
  fixture.detectChanges();

  router.navigate(['dummy']);

  tick(1000);
  fixture.detectChanges();

  expect(router.navigate).toHaveBeenCalledWith(['dummy']);
}));

In a real test, you aren't going to test the navigate() method. In fact, you are going to test some kind of the user behaviour, e.g. click:

In the component (in this case YourComponent):

onClick() {
    this.router.navigate(['dummy']);
}

In the test (replace navigate() by a click trigger):

element.querySelector('button').click();
KGolbang
  • 445
  • 1
  • 5
  • 15