茉莉花 angular 4 单元测试 router.url
jasmine angular 4 unit test router.url
我正在使用 jasmine 对 angular 4 项目中的一个函数进行单元测试,其中的 switch 语句如下所述:
switch(this.router.url) {
case 'firstpath': {
// some code
}
break;
case 'secondpath': {
// some more code
}
break;
default:
break;
}
在我的 spec.ts 文件中。我无法存根或更改 router.url.I 的值希望我的案例执行但默认正在执行。我尝试了不同的方法来设置或 spyOn 和 return 值,但每次 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
不起作用,因为它仅适用于 methods/functions。但是 url
是 属性.
对于使用 Angular 9 及更高版本的人来说 属性 url 现在是只读的 属性 所以 spyOnProperty 不会工作。这也很令人困惑,因为您不会收到错误,但您也不会看到任何“间谍”。
要解决此问题,请使用以下代码:
const mockUrlTree = routerSpy.parseUrl('/mynewpath/myattribute');
// @ts-ignore: force this private property value for testing.
routerSpy.currentUrlTree = mockUrlTree;
在此感谢 Rob post 的回答:
我正在使用 jasmine 对 angular 4 项目中的一个函数进行单元测试,其中的 switch 语句如下所述:
switch(this.router.url) {
case 'firstpath': {
// some code
}
break;
case 'secondpath': {
// some more code
}
break;
default:
break;
}
在我的 spec.ts 文件中。我无法存根或更改 router.url.I 的值希望我的案例执行但默认正在执行。我尝试了不同的方法来设置或 spyOn 和 return 值,但每次 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
不起作用,因为它仅适用于 methods/functions。但是 url
是 属性.
对于使用 Angular 9 及更高版本的人来说 属性 url 现在是只读的 属性 所以 spyOnProperty 不会工作。这也很令人困惑,因为您不会收到错误,但您也不会看到任何“间谍”。
要解决此问题,请使用以下代码:
const mockUrlTree = routerSpy.parseUrl('/mynewpath/myattribute');
// @ts-ignore: force this private property value for testing.
routerSpy.currentUrlTree = mockUrlTree;
在此感谢 Rob post 的回答: