Angular 4 - router.url unit testing

我与影子孤独终老i 提交于 2021-02-07 14:53:55

问题


How do I mock router.url in angular 4 unit testing?

I use router.url in ngOnint in my component but in my test the value for router.url is '/'


回答1:


you could use jasmine spyObj. In you TestBed:

providers:[
 {
 provide: Router,
 usevalue: jasmine.createSpyObj('Router',['methodOne','methodTwo]),
 },
],

in beforeEach:

router = fixture.debugElement.injector.get(Router);

in the test:

it('should...', ()=> {
 (router.methodOne as Spy).and.returnValue(whateverValue)// if you wanna mock the response
});



回答2:


In Angular v9 Router.url is a readonly getter property. You can force the private property value to set the url property:

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



回答3:


This sounds like a solution 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();


来源:https://stackoverflow.com/questions/46271968/angular-4-router-url-unit-testing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!