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. luoguP1401 城市(二分答案+最大流)

    题意 N(2<=n<=200)个城市,M(1<=m<=40000)条无向边,你要找T(1<=T<=200)条从城市1到城市N的路,使得最长的边的长度最小,边不能重复 ...

  2. linux一个网卡添加多个虚IP

    [root@localhost ~]# ifconfig bond0:0 10.0.0.202 netmask 255.255.255.255 broadcast 10.0.0.255 up 摘自:h ...

  3. Incermental GC

    目录 增量式垃圾回收 什么是增量式垃圾回收 三色标记算法 GC 标记清除算法的分割 根查找阶段 标记阶段 写入屏障 清除阶段 分配 优点和缺点 缩短最大暂停时间 降低了吞吐量 Steele 的算法 m ...

  4. 洛谷 P2005 A/B Problem II

    P2005 A/B Problem II 题目背景 为了让大家紧张的心情放松一下,这一题题是一道非常简单的题目. 题目描述 给出正整数N和M,请你计算N div M(N/M的下取整). 输入输出格式 ...

  5. POJ 1258 Agri-Net (最小生成树+Prim)

    Agri-Net Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 39820   Accepted: 16192 Descri ...

  6. STL 之 hash_map源代码剖析

    // Filename: stl_hash_map.h // hash_map和hash_multimap是对hashtable的简单包装, 非常easy理解 /* * Copyright (c) 1 ...

  7. Entity Framework介绍和DBFirst开发方式

    一.ORM概念  什么是ORM? 对象关系映射(英语:(Object Relational Mapping,简称ORM,或O/RM,或O/R mapping),是一种程序技术.简单来说,就是将关系型数 ...

  8. js阻止默认事件与js阻止事件冒泡

    e.stopPropagation(); //阻止事件冒泡 功能:停止事件冒泡 function stopBubble(e) { // 如果提供了事件对象,则这是一个非IE浏览器 if ( e &am ...

  9. HDU 5889 Barricade (Dijkstra+Dinic)

    思路: 首先 先Dijkstra一遍 找出来最短路 不是最短路上的边都不要 然后呢 套个Dinic模板就好了-- 求个最小割 输出 大功告成~~ //By SiriusRen #include < ...

  10. BZOJ 1103 DFS序+线段树

    思路: 先搞出来DFS序 进入这个点 +1 出这个点 -1 线段树维护前缀和 (因为还要修改) 搞定 修改的时候只修改底下节点就OK了 (边权–>点权 不多说) //By SiriusRen # ...