如何对类型为()=> void

时间:2019-07-16 19:40:36

标签: angular typescript jasmine karma-jasmine istanbul

我正在尝试为利用MediaQueryList的组件编写单元测试。我正在竭尽全力地介绍一行,该行将箭头功能分配给变量。

我已经尝试监视函数内部的方法,但是却收到一个错误,提示该方法从未被调用。

我的课:

export class AppComponent implements OnDestroy {
  mobileQuery: MediaQueryList;
  _mobileQueryListener: () => void;

  constructor(
    private changeDetectorRef: ChangeDetectorRef,
    private media: MediaMatcher
  ) {
    this.mobileQuery = this.media.matchMedia('(max-width: 1000px)');
    this._mobileQueryListener = () => this.changeDetectorRef.detectChanges();
    this.mobileQuery.addListener(this._mobileQueryListener);
  }

  ngOnDestroy(): void {
    this.mobileQuery.removeListener(this._mobileQueryListener);
  }
}

我的测试:

it('should setup the media query', () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;

  expect(app.mobileQuery).toBeTruthy();
  expect(app._mobileQueryListener).toEqual(/* ??? */);
});

我想要实现100%的代码覆盖率,并且为此,我需要覆盖_mobileQueryListener的分配。有什么想法吗?

1 个答案:

答案 0 :(得分:0)

我认为您应该尝试检查:

it('should setup the media query', () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;

  expect(app.mobileQuery).toBeTruthy();
  expect(app._mobileQueryListener).toBeDefined();
});

_mobileQueryListener: () => void;只是声明,而不是变量的初始化。因此,请检查它是否已定义。

并验证_mobileQueryListener调用detectChanges()的行为,您可以添加另一个测试用例(确保将public changeDetectorRef放在spy之上):

it('should should call "detectChanges()" from "_mobileQueryListener"', () => {
  const fixture = TestBed.createComponent(AppComponent);
  const app = fixture.componentInstance;
  expect(app._mobileQueryListener).toBeDefined();
  spyOn(app.changeDetectorRef,"detectChanges").and.callThrough();
  app._mobileQueryListener();
  expect(app.changeDetectorRef.detectChanges).toHaveBeenCalled();
});

请注意,将下面的代码移至beforeEach()块,然后全局声明这些变量

  fixture = TestBed.createComponent(AppComponent);
  app = fixture.componentInstance;