Angular 9 - router.RouterTestingModule中的url readonly属性



我正在逐步从Angular 8升级到Angular 10。当到达版本9时,我所有的TestBed.get(Router).url调用都出错了,因为它现在是一个只读属性。

例如:TestBed.get(Router).url = '/map';不再工作

我尝试了一些spyOn选项,并尝试在RouterTestingModule本身提供我的路径,但这些最终没有工作或没有满足我的需求与多条路线。

RouterTestingModule中路径配置的示例:

TestBed.configureTestingModule({
...
providers: [
{
provide: Router,
useValue: {
url: '/path'
} // you could use also jasmine.createSpyObj() for methods
} 
]
});

编辑:在StackOverflow上进一步搜索,我发现了这段有前途的代码:

const mockUrlTree = router.parseUrl('/heroes/captain-marvel');
// @ts-ignore: force this private property value for testing.
router.currentUrlTree = mockUrlTree;

我在这方面也遇到了失败,说明.parseUrl不是路由器上的功能,尽管能够看到它就在serializeUrlisActive之间的类中。

任何关于如何嘲笑我的路径的建议将不胜感激。

有点晚了,但我也有同样的疑问,也许它会帮助别人。基于这个答案,我用以下方式模拟了一个只读字段:

const router: Router = TestBed.inject(Router);
Object.defineProperty(router, url, { value: '/your/path/here' });
Object.defineProperty(router, events, { value: myObservableHere }); // in my case

最新更新