【问题标题】:Jest how to mock api call开玩笑如何模拟 api 调用
【发布时间】:2018-05-05 02:08:09
【问题描述】:

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

(test keep调用原始api调用函数而不是mock)

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

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

【问题讨论】:

    标签: reactjs redux mocking jestjs


    【解决方案1】:

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

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

    【讨论】:

    • 知道如何测试吗? (err, body) => { if (err) { console.error(err.message); } else { dispatch({ type: STUFF.GET, results: body, }); } }
    • 这种方法有什么问题?如果它是调度,你只需要模拟提供给方法的任何东西
    • 谢谢,我想我找到了我想要的 api.call = jest.fn((route = '', callback) => { callback({ message: 'some error' }, null) ; });
    猜你喜欢
    • 2020-03-15
    • 2020-10-20
    • 2021-11-27
    • 2020-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-07-25
    • 2020-08-20
    相关资源
    最近更新 更多