Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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!

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();
                Hi, I can verify that fileUrl is being set and the control does enter the if statement. Regarding the tick(), I am already using fakeAsync. I still tried what you suggested and it still did not work.
– user18631150
                Mar 31, 2022 at 4:51
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.