Reputation: 51
I am trying to test a React table component (that uses an async API call to return table data), but cannot work out how to mock the API call to satisfy my React test file. I have a mock data file to supply mock data. (I have only included relevant code).
mockData:
const mockRequestData = [
{
"email": "[email protected]",
"firstName": "runner1",
"lastName": "runner1"
},
{
"email": "[email protected]",
"firstName": "runner2",
"lastName": "runner2"
},
{
"email": "[email protected]",
"firstName": "runner3",
"lastName": "runner3"
},
];
export const mockData = {
mockData: mockRequestData,
};
apiCall is in its own file:
const getAllAthletesSigningUp = async () => {
let athletesSigningUp= [];
const response = await returnGetResponse("/api/atheletesignup");
if (response.status === 200) {
return athletesSigningUp= (response.body);
}
return athletesSigningUp
};
export {getAllAthletesSigningUp};
runnerTable app:
const [requests, setRequests] = useState([]);
useEffect( () => {
apiResponse();
},[]);
const apiResponse = async () => {
return setRequests(await getAllAthletesSigningUp ())
}
<div className={"table_content"}>
{
requests.map((request, index) => {
return (
<>
<div key={index} className={"table_row"} data-testid={"tableRow"}>
<p>{formatText(request.email)}</p>
<p>{formatText(request.firstName)}</p>
<p>{formatText(request.lastName)}</p>
Upvotes: 0
Views: 934
Reputation: 2745
You can use jest.mock()
:
jest.mock(<path to getAllAthletesSigningUp>, () => ({
getAllAthletesSigningUp: jest.fn(() => [<mock data>])
}))
describe('...', () => {
it('...', () => {
// const {getAllAthletesSigningUp} = jest.requireMock(<path>) - if You need mocked implementation in test;
// const {getAllAthletesSigningUp} = jest.requireActual(<path>) - if You need original implementation in test;
})
})
or describe implementation directly in single test with mockImplementation
or mockImplementationOnce()
:
jest.mock(<path to getAllAthletesSigningUp>, () => ({
getAllAthletesSigningUp: jest.fn()
}))
describe('...', () => {
it('...', () => {
const {getAllAthletesSigningUp} = jest.requireMock(<path>)
// getAllAthletesSigningUp.mockImplementation(() => [<mock data>]) - for all function calls;
// getAllAthletesSigningUp.mockImplementationOnce(() => [<mock data>]) - for single function call;
})
})
Upvotes: 1