'React testing library how to test provider fetch
I have tried several approaches while testing a context provider but failed. It never resolves the fetch call. When I run the coverage, all the components that have been tested hit coverage 100% except for ContextProvider file. The provider has the following methods (functions). save, delete, update. The initial call for the data is done in the useEffect using fetch.
Below I have this code:
useEffect((): void => {
console.log('USE_EFFECT:::::');
fetch('data/data.json')
.then((response: Response): Promise<{data: any}> => {
return response.json();
})
.then((data: any): void => {
console.log('RESOLVING:::::')
setData(data);
setLoading(false);
});}, []);
The console logs are there only to help with debugging the tests, so when I run the tests for this file I only get one log and that is for the 'USE_EFFECT:::::'.
How can I go about testing the context provider by itself as well as mocking the fetch('data/data.json') so that the tests can resolve. How can I also test the methods for this context (save, update, delete)
The provider is returned like so
return <DataContext.Provider value={{
data,
save, //function
update, //function
delete, // function
loading}}>{children}</DataContext.Provider>;
Based on the fact that the components that rely on this context all pass coverage, do I really need to text the context by itself?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
