1

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?

kboul
  • 13,836
  • 5
  • 42
  • 53
Piero
  • 9,173
  • 18
  • 90
  • 160

2 Answers2

4

Use export default instance instead of export {instance}

aaronjkrause
  • 809
  • 5
  • 7
1

main.js

import {instance} from './mock'

Avoid default export - it allows the exported module to be imported with any name.

Best to use named exports (wrapped in {}) to enforce consistent naming in all imports.

barakbd
  • 988
  • 10
  • 16
  • 1
    Named exports can also be imported with any name. `import { foo as bar } from 'bat'`. There is no reason to avoid the default export. It is used based on whatever makes sense for your program. – user2867288 Mar 17 '23 at 21:36