Function not covered in Jest Unit test even though the function was called in a test suite

Viewed 788

I have an <a /> tag which is used as shown below:

 <a class="md-color--blue-50 md-link" (click)="resetdevicesearch()" >Reset filters</a>

In my ts file , this is how the function is defined:

resetdevicesearch() {
    const defaultsearchvalue = {value: {name: 'Any Name/Address', id: 1}};
    this.filterdeviceinfodata = {RisClass: '', Id: '', Name: ''};
    this.deviceonlyclicked = false;
    this.initform();
    this.devicesearch = {name: 'Phone', initial: 'Phone', id: 1};
    this.deviceStatus = this.devicesearchjson.PhoneDevice.DeviceStatus.devicestatusKey;
    this.updatestatus(this.devicesearchjson.PhoneDevice.DeviceStatus.defaultKey);
    this.updatedownloadstatus();
    this.updateProtocol();
    this.devicecheckboxvalue = [];
    this.selecttdefaultcheckbox(this.devicesearchjson.PhoneDevice.Monitorfollowingattribute.monitorfollowingattributeKey);
    this.enableinputfield(defaultsearchvalue);
    this.inputchange = {name: 'Any Name/Address', id: 1, label: ''};
    // @ts-ignore
    this.filterdeviceinfodata = {RisClass: '', Id: '', Name: ''};
  }

Now, I am trying to write an Unit Test to invoke the function. This is how the test suite looks like:

 it('should get the anchor tag', () => {
    fakeAsync(() => {
      spyOn(component, 'resetdevicesearch');
      fixture.detectChanges();
      const input: ElementRef = fixture.debugElement.query(By.css('.md-link'));
      input.nativeElement.blur();
      tick();
      expect(page).toBeTruthy();
      expect(page.anchorTag).toBeTruthy();
      expect(component.resetdevicesearch).toHaveBeenCalled();
  });
  })

Now, the test runs succesfully , but when I check in the coverage folder, it shows Function not covered

enter image description here

Why is this happenning?

Edit:

Modified code:

 it('should get the anchor tag', () => {
    fakeAsync(() => {
      jest.spyOn(component, 'resetdevicesearch');
      fixture.detectChanges();
      const input: ElementRef = fixture.debugElement.query(By.css('.md-link'));
      input.nativeElement.blur();
      tick();
      expect(page).toBeTruthy();
      expect(page.anchorTag).toBeTruthy();
      expect(component.resetdevicesearch).toHaveBeenCalled();
  });
  })
1 Answers

In Jasmine, (or angular default) the spyOn(component, 'resetdevicesearch') mocks the function call, which does not call the underlining function. The solution is simple, replace with:

spyOn(component, 'resetdevicesearch').and.callThrough()

an article on it for your entertainment.

However when using Jest (which is your case) the default is to call through, but you need to use it like this:

jest.spyOn(component, 'resetdevicesearch')
Related