Jest如何模拟api调用

时间:2017-11-21 14:52:38

标签: reactjs redux mocking jestjs

我试图用开玩笑来模仿我的api电话,但由于某种原因它不起作用。我真的不明白为什么。有人有想法吗?

(测试保持调用原始的api调用函数,而不是模拟)

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 个答案:

答案 0 :(得分:4)

导入是不可变的,所以它不会工作,你应该模拟整个模块。使用__mock__目录或只使用:

jest.mock('../../util/api');
const { call } = require('../../util/api');
call.mockImplementation( () => console.log("some api call"));