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. 使用let's encrypt为你的Ubuntu14+nginx网站保驾护航!

    finch最近正在研究一个新的网站系统,闲的没事想搞搞ssl,结果搞了两天,遇到很多问题,现在记录并分享一下经验. 环境之前搭建好了是Ubuntu14+nginx+php5+mysql 现在开始使用l ...

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

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

  3. 手动创建DataTable并添加数据

    DataTable dt=new DataTable(); DataColumn dc=dt.Columns.Add("OBJECTID",Type.GetType("S ...

  4. [Python] Accessing Array Elements

    NumPy Reference: Indexing Note: Indexing starts at 0 (zero). def slicing(): a = np.random.rand(5,4) ...

  5. UvaLive 6600 Spanning trees in a secure lock pattern 矩阵行列式

    链接:https://icpcarchive.ecs.baylor.edu/index.php? option=com_onlinejudge&Itemid=8&page=show_p ...

  6. linux设备驱动归纳总结(三):4.ioctl的实现

    linux设备驱动归纳总结(三):4.ioctl的实现 一.ioctl的简单介绍: 尽管在文件操作结构体"struct file_operations"中有非常多相应的设备操作函数 ...

  7. webpack02

    consumer-index.html <!DOCTYPE html> <html lang="en"> <head> <meta cha ...

  8. OpenSUSE Leap 42.3 安装java(Oracle jre)

    一.安装1.从Oracle官网下载jre-8u161-linux-x64.rpm安装包(下载与浏览器位数一样) 2.安装: openSUSE:/home/pipci # rpm -ivh jre-8u ...

  9. 170703 锐姿公司winserver2012 标准版安装过程

    背景: 锐姿公司一台服务器,配置为:X3650M5 8871 E5 2620V4     32G  双电源  3*1T  raid5  . 原系统由供应商(日闹)上家安装,在安装好的SQL2008,到 ...

  10. mescroll报错

    1.Cannot read property 'insertBefore' of null:说明你的容器id未找到,应确认你的容器id名与你NEW的容器名一致: