Search code examples
javascriptaxiosaxios-mock-adapter

Use axios and axios-mock-adapter


I'm trying to use axios and axios-mock-adapter in one place to aggregate more mocks and then export the axios instance to use it wherever I want:

mock.js

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

let instance = axios.create({
    baseURL: 'https://some-domain.com/api/',
    timeout: 1000,
    headers: {'X-Custom-Header': 'foobar'}
});

let mock = new MockAdapter(instance);
mock.onGet('/users').reply(200, {
    users: [
        { id: 1, name: 'John Smith' }
    ]
});

export {instance}

main.js

import instance from './mock'

instance.get('/users')
  .then(function(response) {
    console.log(response.data);
});

But I get this error:

Uncaught TypeError: Cannot read property 'get' of undefined

Can anyone help me? What did I miss?


Solution

  • Use export default instance instead of export {instance}