How do I mock axios
that export as default function?
I have the api helper that generalizes api request with 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});
});
});
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()
. I don't want to change the definition of the callApi()
function.
How do I mock default axios()
? What did I miss?
You cannot use jest.spyOn(axios, 'default')
when you call axios
directly (no default
). Changing your implementation in api.js
to be axios.default(...args)
makes the test pass.
A potential change you can make is to use jest.mock('axios')
instead of using 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});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With