Jest how to mock api call

Viewed 9193

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