如何模拟导出为默认函数的 axios
?
我有一个 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()
?我错过了什么?
最佳答案
当你直接调用axios
时,你不能使用jest.spyOn(axios, 'default')
(没有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});
});
});
关于javascript - 如何使用 Jest 将 Axios 模拟为默认导出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52275312/