如何对 () => void 类型的变量进行单元测试

How to unit test a variable of type () => void

我正在尝试为使用 MediaQueryList 的组件编写单元测试。我正在努力覆盖一行,它为变量分配了一个箭头函数。

我试过监视函数内部的方法,但我收到一个错误,指出该方法从未被调用过。

我的class:

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 的赋值。有什么想法吗?

我认为你应该尝试检查一下:

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;