IT虾米网

reactjs之Jest 如何模拟 api 调用

52php 2025年12月25日 程序员 31 0

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

(测试保持调用原始api调用函数而不是mock)

我的测试.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")); 


评论关闭
IT虾米网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!