Mock axios with axios-mock-adapter get undefined resp

孤人 提交于 2019-12-05 10:47:59

You don't need axios-mock-adapter. Here is how I mock my axios:

// src/__mocks__/axios.ts

const mockAxios = jest.genMockFromModule('axios')

// this is the key to fix the axios.create() undefined error!
mockAxios.create = jest.fn(() => mockAxios)

export default mockAxios

For more info: https://stackoverflow.com/a/51414152/73323

Two things to try here:

  1. Maybe you already have this elsewhere in your code, but be sure to set up mockAdaptor:

import axios from 'axios';
import MockAdapter from 'axios-mock-adapter';

const mockAdapter = new MockAdapter(axios);
  1. I haven't found a way to get the mock adapter working when the function you are testing uses 'axios.create' to set up a new axios instance. Try something along the lines of this instead:

// api/index.js

const api = {
  get(path) {
    return axios.get('/api' + path)
    .then((response) => {
        return response.data;
    });
  }
}
export default api;

according to James M. advice, I updated my api/index.js , not using the axios.create...

api/index.js

import http from 'axios'

export default {

  fetchShoppingLists: () => {
    console.log('API FETCH SHOPPINGLISTS')
    return http
      .get('http://localhost:3000/shoppinglists')
      .then(response => {
        return response
      })
      .catch(error => {
        console.log('FETCH ERROR: ', error)
      })
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!