javascript - 如何使用 Jest 模拟 Axios 作为默认导出
问题描述
如何axios
将该导出模拟为默认功能?
我有一个概括 api 请求的 api 助手axios()
api.js
export const callApi = (endpoint, method, data = {}) => {
return axios({
url: endpoint,
method,
data
})
.then((response) => // handle response)
.catch((error) => // handle error)
};
api.spec.js
import axios from 'axios';
import { callApi } from './api';
describe('callApi()', () => {
it('calls `axios()` with `endpoint`, `method` and `body`', () => {
// mock axios()
jest.spyOn(axios, 'default');
const endpoint = '/endpoint';
const method = 'post';
const data = { foo: 'bar' };
// call function
callApi(endpoint, method, data);
// assert axios()
expect(axios.default).toBeCalledWith({ url: endpoint, method, data});
});
});
结果
Expected mock function to have been called with:
[{"data": {"foo": "bar"}, "method": "post", "url": "/endpoint"}]
But it was not called.
如果我模拟axios.get()
或其他方法,调用工作正常,但不仅仅是axios()
. 我不想更改callApi()
函数的定义。
我如何模拟默认值axios()
?我错过了什么?
解决方案
jest.spyOn(axios, 'default')
直接调用时不能使用axios
(否default
)。将您的实现更改api.js
为axios.default(...args)
使测试通过。
您可以进行的潜在更改是使用jest.mock('axios')
而不是使用jest.spyOn
.
import axios from 'axios';
import { callApi } from './api';
jest.mock('axios');
// Make sure to resolve with a promise
axios.mockResolvedValue();
describe('callApi()', () => {
it('calls `axios()` with `endpoint`, `method` and `body`', () => {
const endpoint = '/endpoint';
const method = 'post';
const data = { foo: 'bar' };
// call function
callApi(endpoint, method, data);
// assert axios()
expect(axios).toBeCalledWith({ url: endpoint, method, data});
});
});
推荐阅读
- image - Xamarin 形式的图像
- python - Spyder 从 chempy 运行反应系统函数,但不显示与 Jupyter 相同的输出
- cakephp - cakephp 从 2.10 升级到 3.x
- python-3.x - 如何让 plumbum.local 在你的 Windows 系统上运行
- python - 使用 python selenium 遍历一组元素
- html - 表单输入类型提交干扰其他提交
- java - HTTP 动词不是 GET 或 POST 错误(CXF WebServices)
- vue.js - 如何在 createElement 函数中使用 vue3 反应性?
- php - 使用 Doctrine 的 root 和 children 之间的类别差异
- php - PHP 联系表单脚本 - 文件附件