Unhandled Promise rejection: Cannot match any routes

╄→尐↘猪︶ㄣ 提交于 2019-11-30 11:42:26

I had the same problem recently. It was caused by a call to router.navigate inside the ngOnInit method of a component. The test was trying to create the component, but inside ngOnInit it was attempting to navigate away from the component (because certain conditions were not met).

In my case, I am importing the RouterTestingModule as part of TestBed.configureTestingModule. So to fix this I simply registered a route with RouterTestingModule. For example, suppose your navigation call looks like router.navigate(['example']) and it resolves to ExampleComponent. You can set up the test as follows:

RouterTestingModule.withRoutes([
    { path: 'example', component: ExampleComponent}
])

Doing the above allowed my tests to run without issuing Cannot match any routes errors.

For what it's worth, I think a better way would be to stub the router and just confirm that appropriate calls to navigate are made.

To expand on spoida's answer a little, I ended up using a stubbed router:

class RouterStub {
    url = '';
    navigate(commands: any[], extras?: any) { }
}

And then in your providers for your test:

providers: [
    { provide: Router, useClass: RouterStub }
    // ... other providers
]

This resulted in my unit test still passing and removed the console error I was seeing.

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