The way to test router componet needs a little bit setup, first we need to create a "router-stubs.ts". This file is a helper file.

// export for convenience.
export { ActivatedRoute, Router, RouterLink, RouterOutlet} from '@angular/router'; import { Component, Directive, Injectable, Input } from '@angular/core';
import { NavigationExtras } from '@angular/router'; @Directive({
selector: '[routerLink]',
host: {
'(click)': 'onClick()'
}
})
export class RouterLinkStubDirective {
@Input('routerLink') linkParams: any;
navigatedTo: any = null; onClick() {
this.navigatedTo = this.linkParams;
}
} @Component({selector: 'router-outlet', template: ''})
export class RouterOutletStubComponent { } @Injectable()
export class RouterStub {
navigate(commands: any[], extras?: NavigationExtras) { }
} // Only implements params and part of snapshot.paramMap
import { BehaviorSubject } from 'rxjs/BehaviorSubject';
import { convertToParamMap, ParamMap } from '@angular/router'; @Injectable()
export class ActivatedRouteStub { // ActivatedRoute.paramMap is Observable
private subject = new BehaviorSubject(convertToParamMap(this.testParamMap));
paramMap = this.subject.asObservable(); // Test parameters
private _testParamMap: ParamMap;
get testParamMap() { return this._testParamMap; }
set testParamMap(params: {}) {
this._testParamMap = convertToParamMap(params);
this.subject.next(this._testParamMap);
} // ActivatedRoute.snapshot.paramMap
get snapshot() {
return { paramMap: this.testParamMap };
}
} /*
Copyright 2017 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/

The component we want to test:

<app-banner></app-banner>
<app-welcome></app-welcome> <nav>
<a routerLink="/dashboard">Dashboard</a>
<a routerLink="/heroes">Heroes</a>
<a routerLink="/about">About</a>
</nav> <router-outlet></router-outlet>
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html'
})
export class AppComponent { }

Testing setup:

beforeEach( async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent,
BannerComponent, WelcomeStubComponent,
RouterLinkStubDirective, RouterOutletStubComponent
]
}) .compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
});
}));

We need to declare 'RouterLinkStubDirective' & 'RouterOutletStubComponent' which we created in stub helper file.

beforeEach(() => {
// trigger initial data binding
fixture.detectChanges(); // find DebugElements with an attached RouterLinkStubDirective
linkDes = fixture.debugElement
.queryAll(By.directive(RouterLinkStubDirective)); // get the attached link directive instances using the DebugElement injectors
links = linkDes
.map(de => de.injector.get(RouterLinkStubDirective) as RouterLinkStubDirective);
});

Some tests:

it('can get RouterLinks from template', () => {
expect(links.length).toBe(, 'should have 3 links');
expect(links[].linkParams).toBe('/dashboard', '1st link should go to Dashboard');
expect(links[].linkParams).toBe('/heroes', '1st link should go to Heroes');
}); it('can click Heroes link in template', () => {
const heroesLinkDe = linkDes[];
const heroesLink = links[]; expect(heroesLink.navigatedTo).toBeNull('link should not have navigated yet'); heroesLinkDe.triggerEventHandler('click', null);
fixture.detectChanges(); expect(heroesLink.navigatedTo).toBe('/heroes');
});

[Angular & Unit Testing] Testing a RouterOutlet component的更多相关文章

  1. [Angular + Unit Testing] Mock HTTP Requests made with Angular’s HttpClient in Unit Tests

    In a proper unit test we want to isolate external dependencies as much as possible to guarantee a re ...

  2. [Angular & Unit Testing] Testing Component with Store

    When using Ngrx, we need to know how to test the component which has Router injected. Component: imp ...

  3. [Angular Unit Testing] Debug unit testing -- component rendering

    If sometime you want to log out the comonent html to see whether the html render correctly, you can ...

  4. [Angular Unit Testing] Testing Component methods

    import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule ...

  5. [Angular & Unit Testing] Automatic change detection

    When you testing Component rendering, you often needs to call: fixture.detectChanges(); For example: ...

  6. [Angular Unit Testing] Shallow Pipe Testing

    import { TestBed, ComponentFixture } from '@angular/core/testing'; import { BrowserDynamicTestingMod ...

  7. [Angular Unit Testing] Testing Services with dependencies

    import { Http, Response, ResponseOptions } from '@angular/http'; import { TestBed } from '@angular/c ...

  8. [Angular + Unit] AngularJS Unit testing using Karma

    http://social.technet.microsoft.com/wiki/contents/articles/32300.angularjs-unit-testing-using-karma- ...

  9. [AngularJS + Unit Testing] Testing a component with requiring ngModel

    The component test: describe('The component test', () => { let component, $componentController, $ ...

随机推荐

  1. [转载]-win7启动本地MongoDB的四种方式

    2016年04月07日 09:52:34 cherry__cheng 阅读数:19451 标签: win7启动本地MongoDB的四种方式快速启动本地mongodb 更多 个人分类: mongodb& ...

  2. Lenovo k860i 移植Android 4.4 cm11进度记录【下篇--实时更新中】

    2014.8.24 k860i的cm11的移植在中断了近两三个月之后又开始继续了,进度记录的日志上一篇已经没什么写的了,就完结掉它吧,重新开一篇日志做下篇好了.最近的战况是,在scue同学的努力之下, ...

  3. updatedb---创建或更新slocate命令所必需的数据库文件

    updatedb命令用来创建或更新slocate命令所必需的数据库文件.updatedb命令的执行过程较长,因为在执行时它会遍历整个系统的目录树,并将所有的文件信息写入slocate数据库文件中. 补 ...

  4. 【J-meter】调试JDBC请求

    参考资料: http://www.codesec.net/view/165234.html

  5. Android 查看设备信息

    借助getprop.dumpsys来了解一些系统相关信息. 一.getprop adb shell cat /system/build.prop 文件中存放的是用于启动系统时需要的配置文件,通常可以通 ...

  6. FOJ1205 小鼠迷宫问题 (BFD+递推)

    FOJ1205 小鼠迷宫问题 (BFD+递推) 小鼠a与小鼠b身处一个m×n的迷宫中,如图所示.每一个方格表示迷宫中的一个房间.这m×n个房间中有一些房间是封闭的,不允许任何人进入.在迷宫中任何位置均 ...

  7. 基于Linux下Iptables限制BT下载的研究

    基于Linux下Iptables限制BT下载的研究   摘要:     当前BT下载技术和软件飞速发展,给人们网上冲浪获取资源带来了极大的便利, 但同时BT占用大量的网络带宽等资源也给网络和网络管理员 ...

  8. HTTP 各种特性应用(二)

    一.Cookie 通过 Set-Cookie 设置. 下次浏览器请求就会带上. 键值对,可以设置多个. Cookie 属性 max-age 和 expires 设置过期时间 Secure 只在 htt ...

  9. BZOJ3645: Maze(FFT多项式快速幂)

    Description 众维拉先后在中土大陆上创造了精灵.人类以及矮人,其中矮人是生性喜好常年居住在地下的洞穴的存在,他们挖掘矿物甚至宝石,甚至用他们的勤劳勇敢智慧在地底下创造出了辉煌宏大的宫殿,错综 ...

  10. Hexo 添加自定义的内置标签

    灵感 想设计一个记录自已骑行的页面,显示时间.地点.路线图等信息.方便以后做一些留念.定位想实现下面类似的效果.参考:<特效>      实现方案也比较简单,反键查看源码.直接Copy,在 ...