[英]How to mock Axios as default export with Jest
How do I mock axios
that export as default function?如何模拟导出为默认函数的
axios
?
I have the api helper that generalizes api request with axios()
我有使用
axios()
概括 api 请求的 api 助手
api.js 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 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});
});
});
result结果
Expected mock function to have been called with:
[{"data": {"foo": "bar"}, "method": "post", "url": "/endpoint"}]
But it was not called.
The call works fine if I mock axios.get()
or other methods, but not for just axios()
.如果我模拟
axios.get()
或其他方法,调用工作正常,但不仅仅是axios()
。 I don't want to change the definition of the callApi()
function.我不想更改
callApi()
函数的定义。
How do I mock default axios()
?如何模拟默认
axios()
? What did I miss?我错过了什么?
You cannot use jest.spyOn(axios, 'default')
when you call axios
directly (no default
).直接调用
axios
时不能使用jest.spyOn(axios, 'default')
(无default
)。 Changing your implementation in api.js
to be axios.default(...args)
makes the test pass.将
api.js
中的实现更改为axios.default(...args)
使测试通过。
A potential change you can make is to use jest.mock('axios')
instead of using jest.spyOn
.您可以做出的一个潜在改变是使用
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});
});
});
For jest 28
, at least, you can use the following:对于
jest 28
,至少,您可以使用以下内容:
import axios from 'axios'
import { myModule } from '.'
jest.mock('axios')
const mockedAxios = jest.mocked(axios, true)
describe('myModule', () => {
test('response with no errors', async () => {
mockedAxios.mockReturnValue('SUCCESS' as any)
...
expect(mockedAxios).toHaveBeenCalledWith({
URL: 'http://....',
data: { update: 'data' },
method: 'PUT',
...config
})
})
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.