在我的app.component.ts中,我有以下ngOnInit函数:
ngOnInit() {
this.sub = this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
if (!e.url.includes('login')) {
this.loggedIn = true;
} else {
this.loggedIn = false;
}
}
});
}
Run Code Online (Sandbox Code Playgroud)
目前我正在测试sub是否为null但我想测试100%覆盖率的函数.
我想模拟路由器对象,以便我可以模拟URL,然后测试是否正确设置了this.loggedIn.
我将如何进行模拟此功能?我尝试了但是我不知道如何通过涉及的回调和NavigationEnd来实现这一点.
有谁知道我该如何测试Router NavigationEnd Event?我在 Angular 2 中有下面的代码,我正在使用 Jasmine。
import { Injectable, EventEmitter } from '@angular/core';
import { Router, NavigationEnd, Event } from '@angular/router';
@Injectable()
export class IhmPageClassService {
emitPageClass = new EventEmitter<string>();
currentRoute: string;
constructor(router: Router) {
router.events.subscribe((event: Event) => {
if (event instanceof NavigationEnd) {
this.currentRoute = (<NavigationEnd>event).url;
}
});
}
}
Run Code Online (Sandbox Code Playgroud)
谢谢。