My jest test mock of an axios get returns back undefined
as the response and I am not sure what I am doing wrong?
My component that has the axios call is shown below:
const fetchResults = (paramsApi) => {
Service()
.getResults(object)
.then((response) => {
console.log("calling.....", response); // undefined for response, why?
let results = response.data.results;
// more code below but unnecessary to show since response is undefined
Jest test class:
const axios = require("axios");
jest.mock("axios");
describe('AgGridResults', () => {
beforeEach(async () => {
axios.get = jest.fn().mockResolvedValue(
{
data: {
results: {
M0: {
value: [
'Source Id'
]
}
}
}
},
);
render(<AgGridResults searchObject={...} />);
await waitFor(() => expect(screen.getByText('Actions')).toBeInTheDocument())
});
test('AgGridResults', () => {
expect(screen.getByText('Actions')).toBeInTheDocument();
});
});
import axios from 'axios';
function Service() {
return {
getResults: async (searchObject) => {
let urlString = UrlUtility().convert(searchObject);
if (searchObject && urlString) {
return await axios.get('/api/' + urlString + '&pageLength=50');
}
},
getAgreementTypes: async (searchTerm) => {
return await axios.get('/api/' + 'searchString=' + searchTerm);
},
};
}
export default Service;
2
Answers
Mocking Axios when your component doesn’t actually use it creates a brittle coupling. If you ever changed the
Service
implementation, your tests would break.I would instead mock
Service
for your component testTry this out.
https://www.npmjs.com/package/axios-mock-adapter