Unit Test Material Date Picker and more Dialog Fun

March 31, 2022 · 2 min readLucian Ciobanu
Tags:AngularAngularMaterialUnitTest

Looking through the posts I've added over the last year or so, I see a lot of them touching the unit testing and there's no way about it, unit testing for angular is hard and even harderd when various libraries and services come into play.

Just today I had to unit test a function which in certain scenarios opens the angular material date picker after setting it to a variable via @ViewChild decorator as such:

@ViewChild('startpicker') startDatepicker: MatDatepicker<Date>;

...

public openStartDatePicker(): void {
  if (condition) {
    setTimeOut(() => {
      if (this.startDatepicker) {
        this.startDatepicker.open();
      }
    });
  } else {
    this.openModal();
  }
}

Initially I thought I could just spyOn startpicker's open function but I was getting the error "spyOn could not find and object to spy upon for start()"

So this is wthe test I had to write to get the coverage I was aiming for:

...

it('should open datepicker on condition true', fakeAsync(() => {
  //mocking the datepicker
  component.startDatepicker = { open: () => {} } as MatDatepicker<Date>;
  const picker = spyOn(component.startDatepicker, "open");
  component.openStartDatePicker();
  //the function has a setTimeout so we need the fakeAsync and a tick operator
  tick(500);
  expect(picker).toHaveBeenCalled();
}));

Another interesting thing I had to do today was mock the response I got after closing a modal and here is how I did it:

...

it('should something', fakeAsync(() => {
  spyOn(dialog, "open").and.returnValue({afterClosed: () => of{value: true})} as MatDialogRef<unknown>);
   ...
}));

I won't go into more detail, I just wanted to show we can mock a response with as MatDialogRef when the UTs are expecting a certain answer in order to continue executing.

Hope this helped!

Cheers,
Lucian

Picture of author

Web Development & Software Delivery