[Angular & Unit Testing] Testing a RouterOutlet component
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的更多相关文章
- [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 ...
- [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 ...
- [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 ...
- [Angular Unit Testing] Testing Component methods
import {ComponentFixture, TestBed} from '@angular/core/testing'; import {BrowserDynamicTestingModule ...
- [Angular & Unit Testing] Automatic change detection
When you testing Component rendering, you often needs to call: fixture.detectChanges(); For example: ...
- [Angular Unit Testing] Shallow Pipe Testing
import { TestBed, ComponentFixture } from '@angular/core/testing'; import { BrowserDynamicTestingMod ...
- [Angular Unit Testing] Testing Services with dependencies
import { Http, Response, ResponseOptions } from '@angular/http'; import { TestBed } from '@angular/c ...
- [Angular + Unit] AngularJS Unit testing using Karma
http://social.technet.microsoft.com/wiki/contents/articles/32300.angularjs-unit-testing-using-karma- ...
- [AngularJS + Unit Testing] Testing a component with requiring ngModel
The component test: describe('The component test', () => { let component, $componentController, $ ...
随机推荐
- Linux Virtual Server技术
1 LVS简单介绍 Linux VirtualServer是一个高扩展和高可用性server,在一个真正server的集群中构建而成,包括Linux操作系统中的负载均衡. server的架构对于终端用 ...
- 各大IT企业招聘所须要求技能
1.中兴 ZTE 软件研发project师 工作地点:西安.深圳.上海.天津 主要职责: 1.从事通讯产品相关软件开发 2.进行软件具体设计,代码编写.单元測试.集成測试.系统測试等 3.进行软件代码 ...
- 在启动php时,无法启动此程序,由于计算机中丢失MSVCR110.dll的解决方法
在启动php时,运行RunHiddenconsole.exe php-cgi.exe -b 127.0.0.1:9000 -c时,出现错误:无法启动此程序,由于计算机中丢失MSVCR110.dll 方 ...
- CodeForces 550E Brackets in Implications(构造)
[题目链接]:click here~~ [题目大意]给定一个逻辑运算符号a->b:当前仅当a为1b为0值为0,其余为1,构造括号.改变运算优先级使得最后结果为0 [解题思路]: todo~~ / ...
- UE4的JSON读写方式<一>
声明:全部权利保留. 转载必须说明出处:http://blog.csdn.net/cartzhang/article/details/41009343 UE4的Json的解析博客地址: http:// ...
- SQLServer2008 R2安装步骤
1.解压缩sqlserver_2008_r2.iso到指定的目录,记住这个目录的位置 sqlserver_2008_r2.iso下载位置是:http://download.csdn.net/u0123 ...
- caioj1443:第k小的数Ⅲ
[传送门:caioj1443] 简要题意: 给出一颗n个点的树,给出每个点的权值,再给出n-1条边,有m个询问,每个询问输入x,y,k,输出第x节点到第y节点的路径上第k大的点 题解: 这是一道主席树 ...
- php如何截取出视频中的指定帧作为图片
php如何截取出视频中的指定帧作为图片 一.总结 一句话总结:截取视频指定帧为图片,php ffmpeg扩展已经完美实现,并且php ffmpeg是开源的 二.php如何截取出视频中的指定帧作为图片 ...
- 19.浏览器Window服务($window)
转自:https://www.cnblogs.com/best/tag/Angular/ 引用浏览器的window对象.默认浏览器的window是全局的根对象. 示例代码: <!DOCTYPE ...
- IntelliJ IDEA springmvc demo
construction pom.xml <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi=" ...