Jacob Ranson
Jacob Ranson

Reputation: 53

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

I am trying to write unit tests for a component that utilizes MediaQueryList. I am struggling to cover one line, which assigns an arrow function to a variable.

I've tried spying on the method inside the function, but I get an error that the method was never called.

My 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);
  }
}

My test:

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

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

I want achieve 100% code coverage, and to do that, I need to cover the assignment of _mobileQueryListener. Any ideas?

Upvotes: 3

Views: 1397

Answers (1)

Shashank Vivek
Shashank Vivek

Reputation: 17514

I think you should try to check:

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

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

The _mobileQueryListener: () => void; is just declaration and not initialization of the variable. So, check if it defined.

and to verify the behavior of _mobileQueryListener to call detectChanges(), you can add another test case (make sure to have public changeDetectorRef to put spy over it):

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();
});

On side note, move below code to beforeEach() block, and declare those variables globally

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

Upvotes: 1

Related Questions