Problem:
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:
import {AgGridReact} from "ag-grid-react";
import React, {useEffect, useState, useMemo} from 'react';
useEffect(() => {
if(searchObject)
console.log("new being fetched")
fetchResults(gridApi);
}, [searchObject]);
const fetchResults = (paramsApi) => {
Service()
.getResults(searchObject)
.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:
import * as React from 'react';
import { screen } from '@testing-library/dom';
import { render } from '@testing-library/react';
import AgGridResults from "./AgGridResults";
describe('AgGridResults', () => {
beforeEach(async () => {
jest.mock("../../service/Service", () => ({
__esModule: true,
default: () => ({
getResults: async () => ({
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';
import UrlUtility from './urlUtility';
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;
Solution:
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 test
jest.mock("./path/to/service", () => ({
__esModule: true,
default: () => ({
getResults: async () => ({
data: { results: { M0: { value: ["Source ID"] } } },
}),
}),
}));