Jest toHaveBeenCalled is not able to watch the called method

699 Views Asked by At

I am writing unit tests for an Angular application. The method I am trying to test is as follows:

onUrlEntry() {
    const fileUrl = this.componentForm.get('fileUrl');
    
    if(fileUrl?.value) {
      this.URLService
      .getMetadataFromUrl(fileUrl?.value)
      .subscribe((metadataFileContent) => {
        // ...
      }, (err: HttpErrorResponse) => {
        // ...
      });
    }
}

In the spec file, I have created a stub for the fetchURLService > getMetadataFromUrl method:

class URLServiceStub {
  getMetadataFromUrl(url: string) {
    return undefined;
  }
}

I am providing this class inside of TestBed:

providers: [
{ provide: URLService, useClass: URLServiceStub },
]

Here's the Service:

@Injectable({
  providedIn: 'root',
})
export class URLService{
  constructor(private httpClient: HttpClient) {}

  getMetadataFromUrl(url: string) {
    return this.httpClient.get(url, { responseType: 'text' });
  }
}

Now for the unit test:

it('should call getMetadataFromUrl()', fakeAsync(() => {
      const mockMetadataFromUrl = 'testMetaData';

      const getMetadataFromUrlSpy = jest
        .spyOn(URLService , 'getMetadataFromUrl')
        .mockReturnValue(of(mockMetadataFromUrl));

      fixture.detectChanges();
      component.onUrlEntry();

      expect(getMetadataFromUrlSpy).toHaveBeenCalled();
}));

This is not executing. Please help me out.

Thanks!

1

There are 1 best solutions below

2
On

I think you need to make sure fileUrl form value has a value because most likely it does not go inside of the if check.

Try this:

it('should call getMetadataFromUrl()', fakeAsync(() => {
      const mockMetadataFromUrl = 'testMetaData';

      const getMetadataFromUrlSpy = jest
        .spyOn(URLService , 'getMetadataFromUrl')
        .mockReturnValue(of(mockMetadataFromUrl));
      // !! set a value
      component.componentForm.get('fileUrl').setValue('abc');

      fixture.detectChanges();
      component.onUrlEntry();
      // !! wait for the subscription to finish (could be optional)
      tick();
      expect(getMetadataFromUrlSpy).toHaveBeenCalled();
}));