开玩笑如何模拟API呼叫



我试图用开玩笑嘲笑我的API调用,但由于某种原因,它行不通。我真的不明白为什么。有人有一个主意吗?

(测试保持呼叫原始API调用功能,而不是模拟)

我的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动作

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

导入是不可变的,因此它不起作用,您应该模拟整个模块。使用__mock__目录,或者简单地使用:

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

最新更新