【发布时间】:2019-02-15 22:08:19
【问题描述】:
如何模拟 axios 导出为默认函数?
我有一个使用axios()概括api请求的api助手
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()?我错过了什么?
【问题讨论】:
-
方法接受
Object和{method: 'post'}一样,但我可以看到您将它作为普通值而不是对象传递。 -
return axios({ url: endpoint, method: postmethod, data })试试这个 -
我没有收到评论。
callApi()接受普通值。然后它从其纯值参数构造对象并将对象传递给axios()。这就是你想要指出的吗? -
是的,我没有看到
method转换为callApi中的对象。 -
属性同名时的简写对象赋值。这意味着
const foo = { method: method }与const foo = { method }相同。或者如果我错过了任何一点?
标签: javascript axios jestjs