I have a React component as follows. The fetch api is called once the dom load is complete. I want to display the data as a list which is received from the api call.
import React, { useEffect, useState } from "react";
const GetData= () => {
const [isLoading, setIsLoading] = useState(false);
const [lists, setLists] = useState([]);
const [error, setError] = useState('');
useEffect(() => {
const getData = async () => {
try {
const response = await fetch("http://openlibrary.org/people/george08/lists.json");
const data = await response.json();
const { entries } = data;
setLists(entries);
} catch(error) {
setError(error);
}
}
getData();
}, [])
let listContent = <h1>Loading....</h1>;
if (lists.length) {
listContent = (
<ul role='booklist'>
{
lists.map(list => (
<li key={list.url}>{list.name}</li>
))
}
</ul>
)
}
return <>{listContent}</>;
}
export default GetData;
I am very new with React Testing Library. All the example which I am finding are not helping me much in writing the test. Can someone please provide pointers.
Also, I have tried a below test but it did not work for me
it('api success call', async () => {
const mockData = [
{
full_url: "/people/george08/lists/OL95357L/Museum_in_a_Box",
name: "Museum in a Box",
url: "/people/george08/lists/OL95357L"
}
]
const mockedResponse = {
config: {},
data: {
entries: mockData
},
headers: {},
status: 200,
statusText: '200',
}
const mRes = { json: jest.fn().mockResolvedValueOnce(mockedResponse) };
const mockedFetch = jest.fn().mockResolvedValueOnce(mRes);
global.fetch = mockedFetch;
render(<GetData />);
screen.debug();
await act(async () => {
await waitFor(() => expect(mockedFetch).toHaveBeenCalledTimes(1));
});
})