How to correctly use SharedModules with Router while testing angular 2 application?

前端 未结 2 1238
小蘑菇
小蘑菇 2021-01-12 23:15

I\'m trying to unit test a (angular 2) component with routerLink and routerLinkActive but all test cases fail with following error message. (

相关标签:
2条回答
  • 2021-01-13 00:08

    Angular has no way of knowing that you want it to use the activatedRoute variable that you created yourself(as per comment) so it will create default one and use that in DI. Instead of the current setup for the ActivatedRoute dependency use { provide: ActivatedRoute, useValue: mockInstance} where mockInstance is a mock of ActivatedRoute, you can create that with jasmine.createSpyObj

    0 讨论(0)
  • 2021-01-13 00:10

    I have managed to solve this issue. I'll list what changes I made to solve the issue.

    1. As I mentioned in the comments, routerLink works only on real router. So we need to include RouterTestingModule (include .withRoutes([{path: 'some/path',component: someComponent}]) if you plan to click on it while testing).

    2. We need not provide Router dependencies separately if we have added RouterTestingModule already. So I removed both Router and ActivatedRoute dependency that I provided. Now, the error changed from Cannot read property 'subscribe' of undefined to Cannot read property 'outlets' of null.

    3. I found out this error occurs when the routerLink is pointing to a null variable. In my case, the property called favoriteUrl that i assigned to routerLink was null because of the isolated testing environment. So I manually assigned a value to the property in beforeEach function and that solved the problem, atleast for me.

    Thanks to everyone who tried to help! :-)

    References:

    https://stackoverflow.com/a/45916133/8558515

    https://stackoverflow.com/a/42039920/8558515

    0 讨论(0)
提交回复
热议问题