Mock axios with axios-mock-adapter get undefined resp

I created an axios instance ...

// api/index.js

const api = axios.create({
  baseURL: '/api/',
  timeout: 2500,
  headers: { Accept: 'application/json' },
});
export default api;

And modules with numbers are used.

// api/versions.js

import api from './api';

export function getVersions() {
  return api.get('/versions');
}

I'm trying to check how ..

// Test
import { getVersions } from './api/versions';

const versions= [{ id: 1, desc: 'v1' }, { id: 2, desc: 'v2' }];
mockAdapter.onGet('/versions').reply(200, versions);

getVersions.then((resp) => { // resp is UNDEFINED?
  expect(resp.data).toEqual(versions);
  done();
});

Why resp undefined?

+4
source share
2 answers

Two things to try here:

  • You may already have this elsewhere in your code, but be sure to configure mockAdaptor:

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

const mockAdapter = new MockAdapter(axios);
Run codeHide result
  1. I did not find a way to make the adapter layout work when the function under test uses "axios.create" to create a new axios instance. Try something in this direction:

// api/index.js

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

according to the advice of James M., I updated my api / index.js without using 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)
      })
  }
}
0

Source: https://habr.com/ru/post/1678302/


All Articles