[英]Angular 4 - router.url unit testing
如何在 angular 4 單元測試中模擬 router.url?
我在組件中的 ngOnint 中使用了 router.url,但在我的測試中,router.url 的值為 '/'
在 Angular v9 Router.url
是一個只讀的 getter 屬性。 您可以強制私有屬性值設置 url 屬性:
const mockUrlTree = router.parseUrl('/heroes/captain-marvel');
// @ts-ignore: force this private property value for testing.
router.currentUrlTree = mockUrlTree;
你可以使用茉莉花 spyObj。 在你的TestBed
:
providers:[
{
provide: Router,
usevalue: jasmine.createSpyObj('Router',['methodOne','methodTwo]),
},
],
在 beforeEach:
router = fixture.debugElement.injector.get(Router);
在測試中:
it('should...', ()=> {
(router.methodOne as Spy).and.returnValue(whateverValue)// if you wanna mock the response
});
這聽起來像是一個解決方案jasmine angular 4 unit test router.url
const router = TestBed.get(Router);
router.url = '/path/to/anything';
// now you can run your tested method:
component.ngOnint();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.