问题描述
正如标题所示,我需要在单元测试中模拟router.events
.
As the title indicates, I need to mock router.events
in a unit test.
在我的组件中,我做了一些正则表达式来获取url中斜线之间的文本的第一个实例;例如/pdp/
In my component, I doing some regex to grab the first instance of text between slashes in the url; e.g., /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];
}
});
构建组件时,我的单元测试出错误:Cannot read property '0' of null
.当我在调试器中添加注释时,route
似乎没有正确设置,但是我在单元测试本身中对其进行了设置.我已经通过几种不同的方式完成了此工作(受本帖子的启发:嘲笑router.events.subscribe( )Angular2 和其他).
My unit tests error out when the component is being built: Cannot read property '0' of null
. When I comment-in the debugger, route
does not seem to be set correctly, yet I am setting it in the unit test itself. I have done it several different ways (inspired by this post: Mocking router.events.subscribe() Angular2 and others).
第一次尝试:
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: {
parent: {
snapshot: {
url: [
{ path: 'pdp' }
]
}
}
}
}
}
]
第二次尝试(基于以上信息):
Second attempt (based on the above post):
class MockRouter {
public events = of(new NavigationEnd(0, '/pdp/project-details/4/edit', '/pdp/project-details/4/edit'))
}
providers: [
{
provide: Router,
useClass: MockRouter
}
]
第三次尝试(也基于上面的帖子):
Third attempt (also based on above post):
class MockRouter {
public ne = new NavigationEnd(0, '/pdp/project-details/4/edit', '/pdp/project-details/4/edit');
public events = new Observable(observer => {
observer.next(this.ne);
observer.complete();
});
}
providers: [
{
provide: Router,
useClass: MockRouter
}
]
第四次尝试:
beforeEach(() => {
spyOn((<any>component).router, 'events').and.returnValue(of(new NavigationEnd(0, '/pdp/project-details/4/edit', 'pdp/project-details/4/edit')))
...
第五次尝试:
beforeEach(() => {
spyOn(TestBed.get(Router), 'events').and.returnValue(of({ url:'/pdp/project-details/4/edit' }))
...
在上述所有情况下,均未设置route
; NavigationEnd
对象等于:
In all the above cases, route
is not being set; the NavigationEnd
object is equal to:
{ id: 1, url: "/", urlAfterRedirects: "/" }
有想法吗?
推荐答案
它可以很简单:
TestBed.configureTestingModule({
imports: [RouterTestingModule]
}).compileComponents()
...
const event = new NavigationEnd(42, '/', '/');
TestBed.get(Router).events.next(event);
这篇关于Angular 6-如何在单元测试中模拟router.events url响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!