0

I am writing tests to test my saga. Can anyone guide me how I can change the code below so that I can mock the api call? I don`t want to test real data.

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 });
});

The 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;
        });
    }

I have tried to use

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


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

I am having the error

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)
  • If you came up with a different solution please, let us know, otherwise accept my answer. Both could be useful for other users looking for the same answer – NoriSte Mar 27 '19 at 06:11

1 Answers1

-1

I usually do

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

easily exportable as a per-se function

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 };
}

and consumable, in your test

spyUtil(apis, "callApi", jest.fn())
NoriSte
  • 3,589
  • 1
  • 19
  • 18