Khiem
Khiem

Reputation: 157

TypeError: Cannot read property 'subscribe' of undefined in unit test

I'm trying to fix the "should create" unit test of a component. I'm getting the following:

TypeError: Cannot read property 'subscribe' of undefined
    at ElectionResultsChartsComponent.webpackJsonp../src/app/pages/user/election-results/election-results-charts/election-results-charts.component.ts.ElectionResultsChartsComponent.initElectionResultsData (http://localhost:9876/_karma_webpack_/webpack:/src/app/pages/user/election-results/election-results-charts/election-results-charts.component.ts:28:36)
    at new ElectionResultsChartsComponent (http://localhost:9876/_karma_webpack_/webpack:/src/app/pages/user/election-results/election-results-charts/election-results-charts.component.ts:24:10)
    at createClass (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:12481:1)
    at createDirectiveInstance (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:12326:22)
    at createViewNodes (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:13784:38)
    at createRootView (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:13673:1)
    at callWithDebugContext (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:15098:26)
    at Object.debugCreateRootView [as createRootView] (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:14381:1)
    at ComponentFactory_.webpackJsonp../node_modules/@angular/core/esm5/core.js.ComponentFactory_.create (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/core.js:11278:26)
    at initComponent (http://localhost:9876/_karma_webpack_/webpack:/node_modules/@angular/core/esm5/testing.js:1150:1)

election-results-charts.component.spec:

describe('ElectionResultsChartsComponent', () => {
  let component: ElectionResultsChartsComponent;
  let fixture: ComponentFixture<ElectionResultsChartsComponent>;

  const fakeActivatedRoute = {
    snapshot: { data: {} }
}

let mockSomeService = {
  getData: () => {}
}
const mockResultResolver = {
  initElectionResultsData: () => new EmptyObservable()
};

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [
        ChartsModule
      ],
      declarations: [ ElectionResultsChartsComponent ],
      providers: [
        { provide: ActivatedRoute, useValue: fakeActivatedRoute }, 
        { provide: ElectionResultsResolver, useValue: mockResultResolver },
      ]
    })
    .compileComponents();
  }));

  beforeEach(() => {
    fixture = TestBed.createComponent(ElectionResultsChartsComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });
});

election-results-charts.component:

export class ElectionResultsChartsComponent implements OnDestroy {

  private pieChartLabels:string[] = [];
  private pieChartData:number[] = [];
  private pieChartType:string = 'pie';

  private parties: Party[] = [];

  private subData: any;

  constructor(private route: ActivatedRoute) { 
    this.initElectionResultsData();
  }

  initElectionResultsData() {
    this.subData = this.route.data.subscribe(({ data }) => {
      let electionResultResponse: ElectionResultResponse = data;
      for(let party of electionResultResponse.parties) {
        this.pieChartLabels.push(party.name);
        this.pieChartData.push(party.voteCount)
      }
    });   
  }

  ngOnDestroy() {
    this.subData.unsubscribe();
  }

}

election-results-resolver.service:

@Injectable()
export class ElectionResultsResolver implements Resolve<any> {

  constructor(private adminService: ElectionService) { }

  resolve(route: ActivatedRouteSnapshot): Observable<any> {
    let electionRequest: ElectionRequest = {id: +route.paramMap.get('id')}
    return this.adminService.getElectionResults(electionRequest);
  }
}

The component uses a Routing resolver before the page loads. The resolver gets the data and the component pushes the data to the arrays.

Any idea on how I can fix this problem? I have tried to google it, but couldn't find a proper answer for this problem.

Upvotes: 2

Views: 4178

Answers (1)

user4676340
user4676340

Reputation:

  1. you use the routing with ActivatedRoute so you shoudl import the testing module into your application.

Try this :

import { RouterTestingModule } from '@angular/router/testing';

TestBed.configureTestingModule({
      imports: [
        ChartsModule, RouterTestingModule
      ],
....
  1. Your error comes from the fact that your mock doesn't return an Observable. This is because you used a mock in your configuration. Using the RouterTestingModule will allow you to get rid of a provider.

So remove this :

{ provide: ActivatedRoute, useValue: fakeActivatedRoute },
  1. In your future tests, you will have to rewrite the data part of your route. You didn't ask for it, but here is how.

Code :

Object.defineProperty(component.route, 'data', {
  writable: true,
   value: Observable.of({/* everything your data will return must be mocked here */});
});

Upvotes: 3

Related Questions