在Angular 2中测试routerLink指令

时间:2016-05-05 17:32:56

标签: html5 typescript angular angular2-routing angular2-testing

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

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

1 个答案:

答案 0 :(得分:1)

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

   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,因此语法可能会关闭。