Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: (0 , _axios.default) is not a function when use jest.mock('axios') inside a *.test.js file

I try to mock axios module inside my test file like this

// mycomponent.test.js
import axios from 'axios';

jest.mock('axios', () => ({
  get: jest.fn(() => Promise.resolve({ data: 'data' })),
  default: jest.fn(() => Promise.resolve({ data: 'data' })),
}));

But after i add jest.mock('axios') into my test file, i got an error like this.

TypeError: (0 , _axios.default) is not a function

      55 |       this.props.updateGlobalLoading(true);
      56 | 
    > 57 |       axios({
         |       ^
      58 |         method: 'get',
      59 |         url: '/v1/api/portal-xml-list',
      60 |       }).then((res) => {

So how should i fix this, any thing that i missed to set for axios mocking?

Thanks!

like image 724
Varis Darasirikul Avatar asked May 15 '19 07:05

Varis Darasirikul


1 Answers

If you want to mock the default and named exports of a module (axios in this case), the property __esModule must be enabled in the return value:

jest.mock('axios', () => ({
    __esModule: true,
    get: jest.fn(() => Promise.resolve({ data: 'data' })),
    default: jest.fn(() => Promise.resolve({ data: 'data' })),
}));

Alternatively, as it seems that you are only using the default export of axios, you could mock the default export as:

jest.mock('axios', () => jest.fn(() => Promise.resolve({ data: 'data' })));
like image 106
mgarcia Avatar answered Sep 20 '22 01:09

mgarcia