我想知道如何模拟ActivatedRoute网址。
我使用ActivatedRoute
获取当前网址this.activatedRoute.url.subscribe(url => {
this.isEdit = false;
if (url[0].path === 'updatecoc') {
this.isEdit = true;
}
});
所以我想在ActivatedRoute
我试过这个
let fakeActivatedRoute = new MockActivatedRoute();// MockActivatedRoute I have implemented this class from MockActivatedRoute class
fakeActivatedRoute.parent = new MockActivatedRoute();
let urlSegment: UrlSegment[] = [];
urlSegment.push({ path: "updatecoc", parameters: {} });
fakeActivatedRoute.url = Observable.of(urlSegment);
TestBed.configureTestingModule({ { provide: ActivatedRoute, useValue: fakeActivatedRoute }})
但我收到错误:
无法获取未定义或空引用的属性'subscribe'
我不知道我错过了哪里。我该如何解决这个问题?
答案 0 :(得分:1)
我有更好的解决方案:
import { RouterTestingModule } from '@angular/router/testing';
TestBed.configureTestingModule({
imports: [RouterTestingModule],
// ...
})
.compileComponents();
这将模拟你的整个路由模块,现在你可以将你的虚拟模拟注入你的提供者并监视这样的函数
providers: [{provide: ActivatedRoute, useValue: {}}]
当你测试一个函数调用时,让我们说myMock
(我知道它不在其中,它就是这个例子):
const mock = TestBed.get(ActivatedRoute);
spyOn(mock, 'myMock').and.returnValue(/* what you want */);
// ...
expect(mock.myMock).toHaveBeenCalledWith(/* params here */);
编辑我很快就看到了网址是什么,这是你的模拟:
mock.url = jasmine
.createSpy()
.and
.returnValue(new BehaviorSubject({
path: 'yout-mocked-path',
parameters: {/* your mocked parameters */}
})));
答案 1 :(得分:-1)
我已经在谷歌搜索了同样的问题了很多很多时间。没有提供任何答案和线索。所以我去喝茶休息,然后来看看相同的代码。然后我在Facebook上发布了Feeling SAD
帖子。并告诉自己ok, Relax! Relax!
曾经获得一杯茶。
但随便我写了这行代码:fakeActivatedRoute.url = Observable.of(urlSegment);
OH我的上帝! 正在运作。
查看我的完整代码
let fakeActivatedRoute = new MockActivatedRoute();
fakeActivatedRoute.parent = new MockActivatedRoute();
let urlSegment: UrlSegment[] = [];
urlSegment.push({ path: "updatecoc", parameters: {} });
fakeActivatedRoute.parent.url = Observable.of(urlSegment);
fakeActivatedRoute.url = Observable.of(urlSegment);// this was the line made my day beautiful
beforeEach(() => {
TestBed.configureTestingModule({
imports: [FormsModule, MessagesModule, DataTableModule, DropdownModule, ConfirmDialogModule, AccordionModule,
AutoCompleteModule, DialogModule, EditorModule, HttpModule],
declarations: [MaintainCOCComponent],
providers: [{ provide: MaintainCOCService, useClass: MaintainCOCService },
{ provide: Configuration, useClass: Configuration },
{ provide: Router, useClass: MockRouter },
{ provide: ActivatedRoute, useValue: fakeActivatedRoute },
{ provide: VersionDetailsService, useClass: VersionDetailsService },
{ provide: ConfirmationService, useClass: ConfirmationService }]
}).overrideComponent(MaintainCOCComponent, {
set: {
providers: [
{ provide: MaintainCOCService, useClass: MaintainCOCMockService },
{ provide: Configuration, useClass: Configuration }
]
}
});