【问题标题】:How to unit test a variable of type () => void如何对 () => void 类型的变量进行单元测试
【发布时间】:2019-11-25 14:39:26
【问题描述】:

我正在尝试为使用 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 的分配。有什么想法吗?

【问题讨论】:

    标签: angular typescript jasmine karma-jasmine istanbul


    【解决方案1】:

    我认为你应该尝试检查:

    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() 的行为,您可以添加另一个测试用例(确保有publicchangeDetectorRef 将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;
    

    【讨论】:

      猜你喜欢
      • 2011-06-25
      • 2014-02-08
      • 1970-01-01
      • 1970-01-01
      • 2014-05-10
      • 2021-08-02
      • 1970-01-01
      • 1970-01-01
      • 2011-09-17
      相关资源
      最近更新 更多