Home > database >  How to test .pipe with jest with rxjs
How to test .pipe with jest with rxjs

Time:10-29

I have the following service to test

const { data: plan } = await firstValueFrom(
      this.httpService
        .post<CreatePlanPagarmeInterface>(
          `${PagarmeConfig.baseUrl}/plans`,
          pagarmeBody,
          PagarmeConfig.auth,
        )
        .pipe(
          catchError(() => {
            throw new BadRequestException(
              'Error to create plan.',
            );
          }),
        ),
    );

My test

 describe('createPlanMonth', () => {
    it('shoud be able to create a new plan month', async () => {
      jest.spyOn(httpService, 'post').mockReturnValueOnce(
        of({
          status: 200,
          statusText: 'OK',
          config: {},
          headers: {},
          data: resultPagarmeMock,
        }),
      );

      const result = await planService.createPlanMonth(mockPlan);

      expect(result).toEqual(resultMockPlan);
    });
  });

however I'm getting an error when the test arrives in the .pipe

TypeError: Cannot read properties of undefined (reading 'pipe')

CodePudding user response:

Rather than mockReturnValueOnce(of()) you'd need to use mockReturnValueOnce(throwError(() => new AxiosError())) where AxiosError is an error object that takes the same shape as axios's normal error format, it could even be the regular axios error class import { AxiosError } from 'axios';. This way, the observable throws the error and your catchError operator has something to catch and operate on.

CodePudding user response:

My solution:

const response: AxiosResponse<any> = {
    status: 200,
    statusText: 'OK',
    config: {},
    headers: {},
    data: resultPagarmeMock,
  };


describe('createPlanMonth', () => {
    it('shoud be able to create a new plan month', async () => {
      jest.spyOn(httpService, 'post').mockReturnValueOnce(
        of({
          status: 200,
          statusText: 'OK',
          config: {},
          headers: {},
          data: resultPagarmeMock,
        }),
      );

      httpService.post('', { data: mockPlan }).subscribe((res) => {
        expect(res).toEqual(response);
        expect(res.data).toHaveProperty('id');
        expect(res.data).toHaveProperty('status');
      });

      jest.spyOn(repository, 'create').mockResolvedValue(resultMockPlan);

      const result = await repository.create(resultSaveDatabase);

      expect(result).toEqual(resultMockPlan);
      expect(result).toHaveProperty('id');
      expect(result).toHaveProperty('plan_id');
    });
  });
  • Related