How do I mock id = this.route.snapshot.params.id; in angular?

1.1k views Asked by At

I Want to mock this piece of code: (This is a attribute in my component class)

 id = this.route.snapshot.params.id;

I need it for my ActivatedRoute in my test, the error that I get is

cannot read property of 'route' undefined.

the mocking that I have for this is :


 TestBed.configureTestingModule({
       // The declared components needed to test the UsersComponent.
       declarations: [
         MatchEditComponent, // The 'real' component that we will test
         // RouterLinkStubDirective, // Stubbed component required to instantiate the real component.
        
       ],
       imports: [FormsModule],
       //
       // The constructor of our real component uses dependency injected services
       // Never provide the real service in testcases!
       //
       providers: [
         { provide: AuthService, useValue: authServiceSpy },
         { provide: AlertService, useValue: alertServiceSpy },
         { provide: Router, useValue: routerSpy },
         { provide: MatchService, useValue: matchServiceSpy },
         // { provide: StudioService, useValue: studioServiceSpy },
         {
           provide: ActivatedRoute,
           useValue: {
             useValue: {snapshot: {params: {'id': '1'}}}
             
           },
         },
       ],
     }).compileComponents();
 
     fixture = TestBed.createComponent(MatchEditComponent);
     component = fixture.componentInstance;   });
1

There are 1 answers

0
satanTime On

Looks like you nested useValue 2 times:

{
  provide: ActivatedRoute,
  useValue: {
    // useValue again
    useValue: {snapshot: {params: {'id': '1'}}},
  },
}

instead of

{
  provide: ActivatedRoute,
  useValue: {snapshot: {params: {'id': '1'}}},
}