模拟 router.events.subscribe() Angular2 [英] Mocking router.events.subscribe() Angular2
问题描述
在我的 app.component.ts 中,我有以下 ngOnInit 函数:
In my app.component.ts I have the following ngOnInit function:
ngOnInit() {
this.sub = this.router.events.subscribe(e => {
if (e instanceof NavigationEnd) {
if (!e.url.includes('login')) {
this.loggedIn = true;
} else {
this.loggedIn = false;
}
}
});
}
目前我正在测试 sub 是否不为空,但我想以 100% 的覆盖率测试该函数.
Currently I'm testing if the sub is not null but I want to test the function with a 100% coverage.
我想模拟路由器对象,以便我可以模拟 URL,然后测试 this.loggedIn 是否设置正确.
I want to mock the router object so that I can simulate the URL and then test if the this.loggedIn is correctly set.
我将如何继续模拟这个函数?我试过了,但我不知道如何处理涉及的回调和 NavigationEnd.
How would I proceed to mock this function? I tried it but I don't know how I would take this on with the callback involved and with the NavigationEnd.
推荐答案
我已经找到答案了,如果有人在找的话:
I have found the answer, if someone is looking for it:
import { NavigationEnd } from '@angular/router';
import { Observable } from 'rxjs/Observable';
class MockRouter {
public ne = new NavigationEnd(0, 'http://localhost:4200/login', 'http://localhost:4200/login');
public events = new Observable(observer => {
observer.next(this.ne);
observer.complete();
});
}
class MockRouterNoLogin {
public ne = new NavigationEnd(0, 'http://localhost:4200/dashboard', 'http://localhost:4200/dashboard');
public events = new Observable(observer => {
observer.next(this.ne);
observer.complete();
});
}
这篇关于模拟 router.events.subscribe() Angular2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!