Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jest how to mock api call

I am trying to mock my api call with jest but for some reason it's not working. I don't really understand why. Anyone has an idea?

(the test keep call the original api call function and not the mock)

my test.js

import { getStuff } from '../stuff';
import * as api from '../../util/api';

describe('Action getStuff', () => {
        it('Should call the API to get stuff.', () => {
            api.call = jest.fn();
            getStuff('slug')(() => {}, () => {});
            expect(api.call).toBeCalled();
            jest.unmock('../../util/api.js');
        });
});

stuff.js redux action

import api from '@util/api';
import { STUFF, API } from '../constant';


export const getStuff = slug => (dispatch, getState) => {
    const state = getState();
    api.call(API.STUFF.GET, (err, body) => {
        if (err) {
            console.error(err.message);
        } else {
            dispatch({
                type: STUFF.GET,
                results: body,
            });
        }
    }, {
        params: { slug },
        state
    });
};
like image 280
Alexandre Avatar asked Nov 21 '17 14:11

Alexandre


People also ask

How do I test an API call?

API testing flow is quite simple with three main steps: Send the request with necessary input data. Get the response having output data. Verify that the response returned as expected in the requirement.


1 Answers

The import are immutable so it won't work, what you should is mock the whole module. Either with a __mock__ directory or simply with:

jest.mock('../../util/api');
const { call } = require('../../util/api');
call.mockImplementation( () => console.log("some api call"));
like image 155
Axnyff Avatar answered Oct 24 '22 02:10

Axnyff