jd96
jd96

Reputation: 595

How to mock an axios configuration module?

I have a module which configures axios:

// config/axiosConfig.js
import axios from 'axios';

const instance = axios.create({
    baseURL: 'http://localhost:8080/api/v1'
});

export default instance;

And a module that uses this to make api calls:

// store/actions.ts

import axiosInstance from 'config/axiosConfig';

export const fetchUsers = () => (dispatch: ThunkDispatch<{}, {}, AnyAction>) => {
    dispatch(loading(true));
    return axiosInstance.get('/users')
        .then(res => {
            dispatch(loading(false));
            dispatch(fetched(res.data));
        })
        .catch(err => dispatch(error(true)));
}

...

I want to mock the axios config file to test my api file. I've tried many many ways but nothing works. I thought it would be as simple as

// store/actions.test.ts
import axiosInstance from 'config/axiosConfig';

jest.mock('config/axiosConfig');
axiosConfig.get.mockResolvedValue({users: mockUserList});

...

But I guess that's not how it works.


Edit: The approach in my question works when I put axiosConfig.get.mockResolvedValue({users: mockUserList}); inside of the test, not right under the mock call.

Upvotes: 2

Views: 798

Answers (1)

vighnesh153
vighnesh153

Reputation: 5416

Try this out (Put this at the top of the file or at the top inside beforeAll or beforeEach depending on what you prefer):

jest.mock('config/axiosConfig', () => ({
  async get(urlPath) {
    return {
      users: mockUserList,
    };
  },
}));

This is a simple mock using a factory function. To use a mock everywhere, jest provides a better way to avoid repeating yourself. You create a __mocks__ directory and inside that, you can create your module and then override many of the builtins. Then, you can get away with just the following code.

// file.test.ts

jest.mock('fs')

// Rest of your testing code below

Take a look at the official docs to learn more about this.

If this doesn't work, then the module resolution setup in jest.config.js and tsconfig.js might be different.

Upvotes: 1

Related Questions