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. scrapy xpath选择器多级选择错误

    在学习scrapy中用xpath提取网页内容时,有时要先提取出一整个行标签内容,再从行标签里寻找目标内容.出现一个错误. 错误代码: def parse(self, response): sel = ...

  2. 洛谷 P1020 导弹拦截 (LIS)

    第一问最长 不上升子序列,第二问最长上升子序列 套模板就好https://blog.csdn.net/qq_34416123/article/details/81358447 那个神奇的定理当作结论吧 ...

  3. CSU 1510 Happy Robot

    1510: Happy Robot Time Limit: 1 Sec  Memory Limit: 128 MBSubmit: 19  Solved: 7 Description Input The ...

  4. 二 MapReduce 各阶段流程分析

    如果想要将问题变得清晰.精准和优雅, 需要关注 MapReduce 作业所需要的系统资源,尤其是集群内部网络资源使用情况. MR 可以运行在共享集群上处理 TB 级 甚至 PB 级的数据.同时,改作业 ...

  5. [Recompose] Merge RxJS Button Event Streams to Build a React Counter Component

    Combining input streams then using scan to track the results is a common scenario when coding with s ...

  6. Codeforces 528A Glass Carving STL模拟

    题目链接:点击打开链接 题意: 给定n*m的矩阵.k个操作 2种操作: 1.H x 横向在x位置切一刀 2.V y 竖直在y位置切一刀 每次操作后输出最大的矩阵面积 思路: 由于行列是不相干的,所以仅 ...

  7. Sam做题记录

    Sam做题记录 Hihocoder 后缀自动机二·重复旋律5 求一个串中本质不同的子串数 显然,答案是 \(\sum len[i]-len[fa[i]]\) Hihocoder 后缀自动机三·重复旋律 ...

  8. BZOJ 3224 平衡树模板题

    Treap: //By SiriusRen #include <cstdio> #include <algorithm> using namespace std; int n, ...

  9. Weka中数据挖掘与机器学习系列之为什么要写Weka这一系列学习笔记?(一)

    本人正值科研之年,同时也在使用Weka来做相关数据挖掘和机器学习的论文工作. 为了记录自己的学习历程,也便于分享和带领入门的你们.废话不多说,直接上干货!

  10. Android真机调试访问本地服务器(localhost)的解决方案

    Android系统把它自己作为了localhost!当连接localhost都是他自己啊.. 囧,在这里晕了好久才发现.. 网上介绍的都是模拟器连接本地服务器的,我试着把链接改为http://10.0 ...