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. POJ 3567 Cactus Reloaded(仙人掌直径)

    题意 裸的仙人掌直径. 题解 先考虑基环树的直径:先算出每颗“树”的直径,再在环上跑DP 再考虑仙人掌的直径:把每个基环树缩成一条边,边长为基环树深度. #include<iostream> ...

  2. 学习优化《机器学习与优化》中文PDF+英文PDF

    正在学习机器学习中的优化处理,感觉<机器学习与优化>写得还是比较通俗易懂的,第七章特征选择我需要,特征提取:相关系数,相关比,熵和互信息..更高级的应该是文本挖掘的特征提取,比如LDA提取 ...

  3. ubuntu18.04安装dash-to-dock出错的问题

    之前在安装dash-to-dock出现了这种错误: TypeError: ExtensionUtils.initTranslations is not a function Stack trace:i ...

  4. CF 414B Mashmokh and ACM 动态规划

    题意: 给你两个数n和k.求满足以下条件的数列有多少个. 这个数列的长度是k: b[1], b[2], ……, b[k]. 并且 b[1] <= b[2] <= …… <= b[k] ...

  5. 题解 BZOJ4919 【大根堆】

    题面:传送门. 老师说今天要考一道线段树合并,然后...然后这道题我就GG了.(当然可以用线段树合并写,只是比较复杂) 有人赛时想了个贪心,然后被机房巨佬hack了,结果在hack的过程中巨佬想出了正 ...

  6. 题解 P2872 【[USACO07DEC]道路建设Building Roads】

    这道题真的是令人窒息,Kruskal调了贼久一直RE,最后发现数组大小稍微少了那么一点点.(也就10倍吧..) 言归正传,根据本人的分析(以及算法标签的提示),这是一道求最小生成树的题目,当然要注意已 ...

  7. 洛谷—— P1969 积木大赛

    https://www.luogu.org/problem/show?pid=1969 题目描述 春春幼儿园举办了一年一度的“积木大赛”.今年比赛的内容是搭建一座宽度为n的大厦,大厦可以看成由n块宽度 ...

  8. [React] Implement a Higher Order Component with Render Props

    When making a reusable component, you'll find that people often like to have the API they're most fa ...

  9. POJ 3150 Cellular Automaton(矩阵高速幂)

    题目大意:给定n(1<=n<=500)个数字和一个数字m,这n个数字组成一个环(a0,a1.....an-1).假设对ai进行一次d-step操作,那么ai的值变为与ai的距离小于d的全部 ...

  10. Class C++

    为了尽量降低全局变量的使用并提供用户自己定义类型的功能.C++语言提供了一种新的语言机制---类(class).并以类作为构造程序的基本单位 #include<iostream> usin ...