Testing routerLink directive in Angular 2

2019-08-01 18:30发布

问题:

I'm trying to test the work of routing. I moved navbar to a separate component - MdNavbar. Basically only html and css in there, the RouteConfig is in other component and MdNavbar is injected in there. I want to test that route changes when clicking on the link. In test I'm looking for the Profile link and clicking on it. I expect the route to change. Here is the code from my tests -

import {it, inject,async, describe, beforeEachProviders, tick,  fakeAsync} from '@angular/core/testing';

import {TestComponentBuilder} from '@angular/compiler/testing';
import {Component, provide} from '@angular/core';

import {RouteRegistry, Router, ROUTER_PRIMARY_COMPONENT,  ROUTER_DIRECTIVES,RouteConfig} from '@angular/router-deprecated';    
import {Location, LocationStrategy, PathLocationStrategy} from '@angular/common';

import {RootRouter} from '@angular/router-deprecated/src/router';
import {SpyLocation} from '@angular/common/testing';

import {IndexComponent} from '../../home/dashboard/index/index.component';
import {ProfileComponent} from '../../home/dashboard/profile/profile.component';

// Load the implementations that should be tested
import {MdNavbar} from './md-navbar.component';    

describe('md-navbar component', () => {
  // provide our implementations or mocks to the dependency injector
  beforeEachProviders(() => [
    RouteRegistry,
    provide(Location, { useClass: SpyLocation }),
    { provide: LocationStrategy, useClass: PathLocationStrategy },
    provide(Router, { useClass: RootRouter }),
    provide(ROUTER_PRIMARY_COMPONENT, { useValue: TestComponent }),
  ]);

  // Create a test component to test directives
  @Component({
    template: '',
    directives: [ MdNavbar, ROUTER_DIRECTIVES ]
  })
  @RouteConfig([
    { path: '/', name: 'Index', component: IndexComponent, useAsDefault: true },
    { path: '/profile', name: 'Profile', component: ProfileComponent },
  ])
  class TestComponent {}

   it('should be able navigate to profile',
      async(inject([TestComponentBuilder, Router, Location],
        (tcb: TestComponentBuilder, router: Router, location: Location) => {
      return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>')
        .createAsync(TestComponent).then((fixture: any) => {
          fixture.detectChanges();

          let links = fixture.nativeElement.querySelectorAll('a');
          links[8].click()
          expect(location.path()).toBe('/profile');


        //   router.navigateByUrl('/profile').then(() => {
        //     expect(location.path()).toBe('/profile');
        //   })
      })
  })));

Test runs with the following result -

Expected '' to be '/profile'.

And the second one -

Could someone please give me a hint, what exactly I'm doing wrong?

Here is the part navbar component template -

<nav class="navigation mdl-navigation mdl-color--grey-830">
<a [routerLink]="['./Index']" class="mdl-navigation__link" href=""><i class="material-icons" role="presentation">home</i>Home</a>
<a [routerLink]="['./Profile']" class="mdl-navigation__link" href=""><i class="material-icons" role="presentation">settings</i>My Profile</a>
</nav>

ADDED: Thanks to Günter Zöchbauer answer I managed to find a working solution for me.

   it('should be able navigate to profile',
      async(inject([TestComponentBuilder, Router, Location],
        (tcb: TestComponentBuilder, router: Router, location: Location) => {
      return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>')
        .createAsync(TestComponent).then((fixture: any) => {
          fixture.detectChanges();

          let links = fixture.nativeElement.querySelectorAll('a');
          links[8].click();
          fixture.detectChanges();

          setTimeout(() {
            expect(location.path()).toBe('/profile');
          });
      })
  })));

回答1:

The click event is processed async. You would need to delay the check for the changed path.

   it('should be able navigate to profile',
      inject([TestComponentBuilder, AsyncTestCompleter, Router, Location],
        (tcb: TestComponentBuilder, async:AsyncTestCompleter, router: Router, location: Location) => {
      return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>')
        .createAsync(TestComponent).then((fixture: any) => {
          fixture.detectChanges();

          let links = fixture.nativeElement.querySelectorAll('a');
          links[8].click()
          setTimeout(() {
            expect(location.path()).toBe('/profile');
            async.done();
          });


        //   router.navigateByUrl('/profile').then(() => {
        //     expect(location.path()).toBe('/profile');
        //   })
      })
  })));

or

   it('should be able navigate to profile',
      async(inject([TestComponentBuilder, Router, Location],
        (tcb: TestComponentBuilder, router: Router, location: Location) => {
      return tcb.overrideTemplate(TestComponent, '<md-navbar></md-navbar>')
        .createAsync(TestComponent).then((fixture: any) => {
          fixture.detectChanges();

          let links = fixture.nativeElement.querySelectorAll('a');
          links[8].click()
          return new Promise((resolve, reject) => {
            expect(location.path()).toBe('/profile');
            resolve();
          });


        //   router.navigateByUrl('/profile').then(() => {
        //     expect(location.path()).toBe('/profile');
        //   })
      })
  })));

I'm not using TypeScript myself, therefore syntax might be off.