Home > Software engineering >  Testing .pipe in Angular Jest
Testing .pipe in Angular Jest

Time:01-27

I would like to test the following .ts file:

create(entityResourceID, params: any): Observable <any>{
  const url = `${this.apiUrl}/${entityResourceID}/assignee`;
  return this.http.post(url, params).pipe(
    map(() => { this.toaster.success('Successfully Asssigned Email'); }),
    catchError((error) => [
      console.error(error),
      this.toaster.error('Failed Assigning Email')
    ])
  );
}

however I am currently getting the error .pipe is not a function

here is my test spec.ts file currently:

describe('create', () => {
    it('should return a valid url', () => {
        const spy = jest.spyOn(mockHttpClient, 'post').mockReturnValue('test');
        const result = component.create(testEntityID, {});
        expect(spy).toBeCalledWith('entities/url/assignee', {});
        expect(result).toStrictEqual('test');
    });
});

I understand that is made difficult because I am returning a type Observable. I need to return an Observable from my spy so I can test both of my cases, but how exactly would I do that?

CodePudding user response:

This error is because you mock the post method and return a string value instead of an Observable with your value inside. I dont know if you are using rxjs, but you can do something like this..

import { of } from 'rxjs';

const spy = jest.spyOn(mockHttpClient,'post').mockReturnValue(of('test'));

of method is a short way of Obeservable.of(yourValueHere)

  • Related