7

I created an axios instance ...

// api/index.js

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

And severals modules use it ..

// api/versions.js

import api from './api';

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

I try to test like ..

// 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 is undefined?

skyboyer
  • 15,149
  • 4
  • 41
  • 56
ridermansb
  • 9,589
  • 20
  • 104
  • 197

3 Answers3

4

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;
James M
  • 153
  • 6
  • #1. I already set up this. #2. Just use `new MockAdapter(axiosInstanceHere);` no need to do that. – ridermansb Jun 02 '17 at 04:38
  • using ```new MockAdapter(axios.create({timeout: 5000}))``` does not work. – sjt003 Aug 28 '17 at 17:57
  • I am having the same problem. When created the connection with `axios.create` the mock adapter returns undefined. – DaKaZ Aug 30 '17 at 17:34
  • thanks a lot you put me on track... I updated the api.index.js, not using anymore axios.create ! I'll update my question with the right coding following your recommendation –  Sep 12 '17 at 07:15
  • thanks a lot you put me on track... I updated the api.index.js, not using anymore axios.create ! I'll update my question with the right coding following your recommendation –  Sep 12 '17 at 07:15
-1

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

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

kyw
  • 4,313
  • 5
  • 34
  • 46