TypeError:无法读取属性' subscribe'在单元测试中未定义

时间:2018-06-01 13:01:38

标签: angular unit-testing typescript karma-runner karma-jasmine

我试图修复"应该创建"组件的单元测试。我得到以下内容:

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)

选举结果的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();
  });
});

选举结果的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();
  }

}

选举结果的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);
  }
}

组件在页面加载之前使用路由解析程序。解析器获取数据,组件将数据推送到数组。

有关如何解决此问题的任何想法?我试图谷歌它,但无法找到解决这个问题的正确答案。

1 个答案:

答案 0 :(得分:3)

  1. 您使用ActivatedRoute路由,因此您需要将测试模块导入您的应用程序。
  2. 试试这个:

    import { RouterTestingModule } from '@angular/router/testing';
    
    TestBed.configureTestingModule({
          imports: [
            ChartsModule, RouterTestingModule
          ],
    ....
    
    1. 您的错误来自于您的模拟不会返回Observable这一事实。这是因为您在配置中使用了模拟。使用RouterTestingModule将允许您摆脱提供者。
    2. 所以删除它:

      { provide: ActivatedRoute, useValue: fakeActivatedRoute },
      
      1. 在将来的测试中,您必须重写路线的data部分。你没有要求它,但这是如何。
      2. 代码:

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