在Angular 2中测试routerLink指令 [英] Testing routerLink directive in Angular 2

查看:167
本文介绍了在Angular 2中测试routerLink指令的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

第二个 -

可能有人请给我一个提示,我到底做错了什么?

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>

增加:
感谢GünterZöchbauer回答我设法为我找到一个有效的解决方案。

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


推荐答案

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

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

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

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

这篇关于在Angular 2中测试routerLink指令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆