fransyozef
fransyozef

Reputation: 574

Angular unit testing TypeError: Cannot read property 'subscribe' of undefined

I'm creating starter kit template with auth and a example with CRUD (https://github.com/fransyozef/basic-login-angular)

Now I'm new with unit testing and i'm trying to get atleast get the testing running that the components are created. But I'm getting stuck with

TypeError: Cannot read property 'subscribe' of undefined

I think the error comes from

  resolveRoute() {
    this.route.params.subscribe(params => {
      if (params['id']) {
        this.id = +params['id'];
        this.getItem();
      } else {
        this.handleItemNotFound();
      }
     });
  }

in the file https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.ts

Right now I have the testfile : https://github.com/fransyozef/basic-login-angular/blob/master/src/app/items/item-edit/item-edit.component.spec.ts

Can somebody give me a hand with this?

Upvotes: 1

Views: 6277

Answers (1)

billyjov
billyjov

Reputation: 2970

You should mock your routing strategy. As i can see you use a routingModule inside your TestBed imports. Assume that your own routingModule only provide your own routes and will not be able to mock/spy another routes. So I will encourage you to adjust first your Test helper routes inside test.helper.ts

export const TestRoutingImports = [
  HttpClientTestingModule,
  RouterTestingModule, // <-- Use RouterTestingModule instead
]; 

The(RouterTestingModule) modules sets up the router to be used for testing. It provides spy implementations of Location, LocationStrategy, and NgModuleFactoryLoader.

RouterTestingModule provide mocks, RouterModule not.

The second thing you should do is to remove your provide from the Testbed. It's here not necessary. I mean the following part:

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

Remove this because this will be a Overriding of the components providers. In your case it's not needed.

I hope i could help you.

Upvotes: 1

Related Questions