Как издеваться над вызовом API в шутку для теста саги - PullRequest
0 голосов
/ 05 марта 2019

Я пишу тесты для проверки моей саги. Кто-нибудь может подсказать мне, как я могу изменить код ниже, чтобы я мог издеваться над вызовом API? Я не хочу проверять реальные данные.

import { call, put } from 'redux-saga/effects';

import { API_BUTTON_CLICK_SUCCESS, } from './actions/consts';
import { getDataFromAPI } from './api';

it('apiSideEffect - fetches data from API and dispatches a success action', () => {
  const generator = apiSideEffect();

  expect(generator.next().value)
    .toEqual(call(getDataFromAPI));

  expect(generator.next().value)
    .toEqual(put({ type: API_BUTTON_CLICK_SUCCESS }));

  expect(generator.next())
    .toEqual({ done: true, value: undefined });
});

getDataFromAPI ()

import axios from "axios";

export const getDataFromAPI =(
  method: string,
  url: string,
  path: string,
  data?: any
) =>{
  switch (method) {
    case "create": {
      return axios
        .post(url + path, data, {
          headers: {
            Accept: "application/json",
            "content-type": "application/json"
          }
        })
        .catch(error => {
          throw error.response;
        });
    }

Я пытался использовать

jest.mock('../../src/Utilities/api');
const { callApi } = require('../../src/Utilities/api');


callApi.mockImplementation( () => console.log("some api call"));

У меня ошибка

TypeError: Cannot read property 'mockImplementation' of undefined

  at Object.<anonymous> (src/Payments/PaymentSagas.spec.ts:10:17)
      at new Promise (<anonymous>)
  at Promise.resolve.then.el (node_modules/p-map/index.js:46:16)
      at <anonymous>
  at process._tickCallback (internal/process/next_tick.js:188:7)

1 Ответ

0 голосов
/ 11 марта 2019

Я обычно делаю

import * as apis from '../../src/Utilities/api';
jest.spyOn(api, "callApi");
api.callApi.mockImplementation(/* your mock */);

, легко экспортируемый как функция per se,

export function spyUtil(obj, name, mockFunction = undefined) {
  const spy = jest.spyOn(obj, name);
  let mock;
  if (mockFunction) {
    mock = jest.fn(mockFunction);
    obj[name].mockImplementation(mock);
  }
  return { spy, mock };
}

и расходный материал, в вашем тесте

spyUtil(apis, "callApi", jest.fn())
...