如标题所示,我需要router.events在单元测试中进行模拟。
在我的组件中,我做了一些正则表达式来获取url中斜线之间的文本的第一个实例;例如,/pdp/
constructor(
private route: ActivatedRoute,
private router: Router,
}
this.router.events.pipe(takeUntil(this.ngUnsubscribe$))
.subscribe(route => {
if (route instanceof NavigationEnd) {
// debugger
this.projectType = route.url.match(/[a-z-]+/)[0];
}
});
Run Code Online (Sandbox Code Playgroud)
构建组件时,我的单元测试出错误:Cannot read property '0' of null。当我在调试器中添加注释时,route似乎没有正确设置,但是我在单元测试中对其进行了设置。我已经通过几种不同的方式完成了此工作(受本篇文章的启发:模拟router.events.subscribe()Angular2等)。
第一次尝试:
providers: [
{
provide: Router,
useValue: {
events: of(new NavigationEnd(0, '/pdp/project-details/4/edit', 'pdp/project-details/4/edit'))
}
},
// ActivatedRoute also being mocked
{
provide: ActivatedRoute,
useValue: {
snapshot: { url: [{ path: 'new' }, { path: 'edit' }] },
parent: { …Run Code Online (Sandbox Code Playgroud)