亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何模擬 axios 配置模塊?

如何模擬 axios 配置模塊?

暮色呼如 2023-12-14 14:20:33
我有一個配置 axios 的模塊:// config/axiosConfig.jsimport axios from 'axios';const instance = axios.create({    baseURL: 'http://localhost:8080/api/v1'});export default instance;以及一個使用它來進行 api 調用的模塊:// store/actions.tsimport axiosInstance from 'config/axiosConfig';export const fetchUsers = () => (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {    dispatch(loading(true));    return axiosInstance.get('/users')        .then(res => {            dispatch(loading(false));            dispatch(fetched(res.data));        })        .catch(err => dispatch(error(true)));}...我想模擬 axios 配置文件來測試我的 api 文件。我嘗試了很多很多方法但沒有任何效果。我以為這會很簡單// store/actions.test.tsimport axiosInstance from 'config/axiosConfig';jest.mock('config/axiosConfig');axiosConfig.get.mockResolvedValue({users: mockUserList});...但我想事情并不是這樣的。axiosConfig.get.mockResolvedValue({users: mockUserList});編輯:當我放入測試內部而不是放在模擬調用下時,我的問題中的方法有效。
查看完整描述

1 回答

?
揚帆大魚

TA貢獻1799條經驗 獲得超9個贊

嘗試一下(將其放在文件頂部或內部頂部beforeAll或beforeEach取決于您的喜好):


jest.mock('config/axiosConfig', () => ({

? async get(urlPath) {

? ? return {

? ? ? users: mockUserList,

? ? };

? },

}));

這是使用工廠函數的簡單模擬。到處使用模擬jest提供了一種更好的方法來避免重復。您創建一個__mocks__目錄,然后在其中創建模塊,然后覆蓋許多內置函數。然后,您只需使用以下代碼即可擺脫困境。


// file.test.ts


jest.mock('fs')


// Rest of your testing code below


如果這不起作用,則 和 中的模塊分辨率設置jest.config.js可能tsconfig.js會有所不同。


查看完整回答
反對 回復 2023-12-14
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號