Как проверить вызовы HttpService.Post с помощью jest - PullRequest
0 голосов
/ 22 января 2020

Я вызываю API в сервисе nest js, как показано ниже,

import { HttpService, Post } from '@nestjs/common';

export class MyService {

constructor(private httpClient: HttpService) {}

public myMethod(input: any) {
    return this.httpClient
      .post<any>(
        this.someUrl,
        this.createObject(input.code),
        { headers: this.createHeader() },
      )
      .pipe(map(response => response.data));
  }
}

Как я могу издеваться / шпионить за вызовом this.httpClient.post (), чтобы вернуть ответ, не нажимая на актуальный API?

describe('myMethod', () => {
    it('should return the value', async () => {
      const input = {
        code: 'value',
      };
      const result = ['test'];

      // spyOn?

      expect(await myService.myMethod(input)).toBe(result);
  });
});

1 Ответ

1 голос
/ 22 января 2020

Получил работу с помощью spyOn.

describe('myMethod', () => {
    it('should return the value', async () => {
      const input = {
        code: 'mock value',
      };

      const data = ['test'];

      const response: AxiosResponse<any> = {
        data,
        headers: {},
        config: { url: 'http://localhost:3000/mockUrl' },
        status: 200,
        statusText: 'OK',
      };

      jest
        .spyOn(httpService, 'post')
        .mockImplementationOnce(() => of(response));

      myService.myMethod(input).subscribe(res => {
        expect(res).toEqual(data);
      });
  });
});
...