I am trying to execute unit test a (angular 2) with routerLink and routerLinkActive , but all test cases fail with a subsequent error message. ( Note: I pinned the router and other related dependencies. Here is the link I used for this.).
Unable to read subscribe property undefined
I also noticed that when routerLink and routerLinkActive are removed from my template, all test cases will run without any errors.
I think that the error is caused by either RouterTestingModule or SharedModule (contains a component for displaying and checking the password input field). So I tried deleting or adding them to find what was actually causing the problem. Here is what I observed.
- I get a '
Cannot read property 'subscribe' of undefined' if RouterTestingModule or SharedModule . - I do not get any router related error only if I delete both the
RouterTestingModule and the SharedModules , but the elements from the SharedModules will not be loaded into the component and some of them will fail due to this.
TestBed Configuration:
TestBed.configureTestingModule({ imports: [CoreModule,SharedModule,RouterTestingModule], declarations: [ MyComponent,RouterLinkStubDirective,RouterOutletStubComponent ], providers: [ FormBuilder, { provide: Router, useClass: RouterStub }, { provide: ActivatedRoute, userClass: ActivatedRouteStub} ], schemas: [NO_ERRORS_SCHEMA] }) .overrideComponent(MyComponent, { set: { providers: [ {provide: AuthModel, useClass: MockAuthModel} ], } }) .compileComponents(); }));
ActivatedRouterStub:
@Injectable() export class ActivatedRouteStub { // ActivatedRoute.params is Observable private subject = new BehaviorSubject(this.testParams); params = this.subject.asObservable(); // Test parameters private _testParams: {}; get testParams() { return this._testParams; } set testParams(params: {}) { this._testParams = params; this.subject.next(params); } // ActivatedRoute.snapshot.params get snapshot() { return { params: this.testParams }; } }
What changes should I make to solve the problem?
source share