【问题标题】:How to mock an axios configuration module?如何模拟 axios 配置模块?
【发布时间】:2021-03-28 23:16:43
【问题描述】:

我有一个配置 axios 的模块:

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

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

export default instance;

还有一个使用它来进行 api 调用的模块:

// 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)));
}

...

我想模拟 axios 配置文件来测试我的 api 文件。我尝试了很多很多方法,但没有任何效果。我以为它会很简单

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

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

...

但我想这不是它的工作原理。


编辑:当我将axiosConfig.get.mockResolvedValue({users: mockUserList}); 放在测试中时,我的问题中的方法有效,而不是在模拟调用下。

【问题讨论】:

  • 看起来你做对了,但我需要看看你的完整测试

标签: javascript typescript axios jestjs


【解决方案1】:

试试这个(根据你的喜好,把它放在文件的顶部或beforeAllbeforeEach 的顶部):

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

这是一个使用工厂函数的简单模拟。要在任何地方使用模拟,jest 提供了一种更好的方法来避免重复自己。您创建一个__mocks__ 目录,在其中,您可以创建您的模块,然后覆盖许多内置函数。然后,您只需使用以下代码即可。

// file.test.ts

jest.mock('fs')

// Rest of your testing code below

查看official docs 了解更多信息。

如果这不起作用,则jest.config.jstsconfig.js 中的模块分辨率设置可能不同。

【讨论】:

  • 非常感谢,成功了。介意解释为什么?另外,如果我希望 get 方法在不同的测试中返回不同的东西,这是否适用于这个设置?即在每个测试中覆盖 get 函数的模拟。
  • 是的。您只需在每个测试文件中重复这些步骤,并在 get 方法中设置您想要返回的任何内容(为避免重复,您可以将其提取到单独的模块中并用它做一些有趣的事情)。这是一个简单的模拟,我们提供了一个工厂。您的方法需要一些设置,例如设置__mocks__ 目录等。我还更新了答案的原因。看看吧。
猜你喜欢
  • 1970-01-01
  • 2019-11-14
  • 1970-01-01
  • 1970-01-01
  • 2019-11-20
  • 1970-01-01
  • 2021-06-09
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多