jasmine angular 4单元测试路由器.url
我正在使用jasmine对angular 4项目中的一个函数进行单元测试,jasmine的开关语句如下所述:jasmine angular 4单元测试路由器.url,angular,unit-testing,karma-jasmine,router,Angular,Unit Testing,Karma Jasmine,Router,我正在使用jasmine对angular 4项目中的一个函数进行单元测试,jasmine的开关语句如下所述: switch(this.router.url) { case 'firstpath': { // some code } break; case 'secondpath': { // some more code } brea
switch(this.router.url) {
case 'firstpath': {
// some code
}
break;
case 'secondpath': {
// some more code
}
break;
default:
break;
}
在我的spec.ts文件中。我无法存根或更改router.url的值。我希望执行我的案例,但默认值正在执行。我尝试了不同的方法来设置或spyOn并返回值,但每次url都是“/”。每一个建议或解决方案都将受到欢迎 首先,您需要在测试模块中模拟路由器:
TestBed.configureTestingModule({
...
providers: [
{
provide: Router,
useValue: {
url: '/path'
} // you could use also jasmine.createSpyObj() for methods
}
]
});
您还可以在测试中更改url并运行测试方法:
const router = TestBed.inject(Router);
// @ts-ignore: force this private property value for testing.
router.url = '/path/to/anything';
// now you can run your tested method:
component.testedFunction();
正如您所提到的,spyOn不起作用,因为它只适用于方法/函数。但是
url
是一个属性。对于使用Angular 9及以上属性的人来说,url现在是一个只读属性,因此spyOnProperty将不起作用。这也让人困惑,因为你不会出错,但你也不会看到任何“间谍活动”
要解决此问题,请使用以下代码:
const mockUrlTree = routerSpy.parseUrl('/mynewpath/myattribute');
// @ts-ignore: force this private property value for testing.
routerSpy.currentUrlTree = mockUrlTree;
感谢Rob在本文中给出的答案:
@martin你是我的救世主!我尝试使用
spyOnProperty(spyRouter,'url','get')和.returnValue('test')代码>但它没有那么安静。在使用router.url='/path/to/anything'时,我遇到了一个错误“TypeError:无法设置只有getter的[object object]的属性url”。如果您在Christoper Grigg的注释中遇到错误,路由器可能无法正确模拟。您可以尝试spyOnProperty
并将其用作spyOnProperty(路由器,'url','get')。和.returnValue('yourUrl')
我们可以使用RouterTestingModule
做类似的事情吗?@martinuc,非常感谢您的回答。它还解决了我的路由器juni测试问题。