简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM