问题描述
我正在学习 Angular,我想做测试,但我被卡住了.我有一个功能:
I'm learning Angular and I want to do tests, but I'm stuck. I've got a function:
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) =>
this.SomethingService.getSomething(params.get('id')))
.subscribe(something => {
this.something = something;
this.doSomethingElse();
});
}
哪里
route: ActivatedRoute
我想测试它但我不知道如何模拟 ActivatedRoute
and I want to test it but I don't know how to mock ActivatedRoute
推荐答案
一种模拟 ActivatedRoute
的简单方法是这样的:
A simple way to mock ActivatedRoute
is this one:
TestBed.configureTestingModule({
declarations: [YourComponenToTest],
providers: [
{
provide: ActivatedRoute,
useValue: {
params: Observable.from([{id: 1}]),
},
},
]
});
然后在您的测试中它将可用并且您的函数应该可以使用它(至少是 ActivatedRoute 部分)
Then in your test it will be available and your function should work with this (at least the ActivatedRoute part)
如果您想将其存储在变量中,您可以在 it
函数中使用 TestBed.get(ActivatedRoute)
获取它.
You can get it with TestBed.get(ActivatedRoute)
in your it
functions if you want to stock it in a variable.
不要忘记从 rxjs/Rx
而不是从 rxjs/Observable
Don't forget to import Observable from rxjs/Rx
and not from rxjs/Observable
这篇关于你如何模拟 ActivatedRoute的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!