0

I have the following component which displays a list of items as cards fetched using the fetch api call from a data.json file.

const [items, setItems] = useState([]);

useEffect((): void => {
    getData().then((response: any): void => {
        
        if (!items) {
            const collection = response.data.items;
            
            setItems(collection);
        }
        
    }); 
});

return (
    <div className="Items-container">
        {
            items?.map((i: any, index: number): any => {
                return (
                    <button className="Items-cardAction Items-card" key={index}>
                        <div className="Items-imageContainer">
                            <img className="Items-image Items--imageRounded" src={i.image} alt=""/>
                        </div>
                        <h3 className="Items-name">{i.name}</h3>
                        <p>{i.location}</p>
                        <p>{i.plan}</p>
                        <p>{i.age}</p>
                    </button>
                )
            })
        }
    </div>
)

The fetch method:

const getData=()=>{
return fetch('data.json'
    ,{
        headers : {
            'Content-Type': 'application/json',
            'Accept': 'application/json'
        }
    }
  )
}

If I use this component in App.tsx, how do I go about testing it's use in App.tsx. Also how do I go about testing this component and what it does (calls the api, uses the data from the api call to populate the dom with 'cards'). Also what should I be testing here. Should I concentrate on testing the data, or the dom? Or function calls? Some of the documentation from testing library and jest doesn't really give much on such scenarios.

Chief
  • 854
  • 12
  • 27
  • https://jestjs.io/docs/asynchronous#promises shows you how to test promises using Jest. I recommend looking at https://jestjs.io/docs/tutorial-react also, which shows you how to test React. Regarding what to test, definitely test `getData()` and the component itself. I would recommend looking into TDD and start writing tests before your code to ensure your code is resilient and well tested. – Will Walsh Jun 14 '21 at 22:37
  • Yeah I'm aware of TDD but I prefer no to take that approach. will also have a look at the links you have provided. also I'm somewhat familiar and competent with karma/jasmine testing because of angular – Chief Jun 15 '21 at 17:07

0 Answers0