在 Angular 2 中测试 routerLink 指令

Testing routerLink directive in Angular 2

我正在尝试测试路由的工作。我将导航栏移动到一个单独的组件 - MdNavbar。基本上只有 html 和 css 在那里,RouteConfig 在其他组件中,MdNavbar 被注入在那里。我想测试单击 link 时路由的变化。在测试中,我正在寻找配置文件 link 并单击它。我希望路线会改变。这是我测试的代码 -

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');
        //   })
      })
  })));

测试运行结果如下 -

Expected '' to be '/profile'.

第二个 -

有人可以给我提示吗,我到底做错了什么?

这是部分导航栏组件模板 -

<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>

已添加: 感谢 Günter Zöchbauer 的回答,我设法为我找到了一个可行的解决方案。

   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');
          });
      })
  })));

点击事件被异步处理。您需要延迟检查更改后的路径。

   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');
        //   })
      })
  })));

   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');
        //   })
      })
  })));

我自己没有使用 TypeScript,因此语法可能不对。