I'm using React context and I have a React context file that performs a fetch on a JSON file (replicating an API fetch) and returns a bunch of products, I use the products data on a few different pages in my website and is working fine:
// context/index.js
const [products, setProducts] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
const fetchData = async () => {
const res = await fetch("../../products.json");
const { ProductCollection } = await res.json();
setProducts(ProductCollection);
setLoading(false);
};
fetchData();
}, [setProducts, setLoading]);
I have a separate component, I import the the products data from context/index.js to my home page component and render it which works fine:
// Home/index.js
function Home() {
const appContext = useContext(ComputerContext);
const { products } = appContext; // products is an array of objects
//... do stuff and render products
I'm trying to test this using Jest:
// Home/Home.test.js
import React from "react";
import { render } from "@testing-library/react";
import Home from "../Home";
it("renders without crashing", () => {
render(<Home />);
});
But I get the error below. Obviously I need the product data in my Home.test.js file.
What's the best way to achieve this?
TypeError: Cannot destructure property 'products' of 'appContext' as it is undefined.
7 | const [categories, setCategories] = useState([]);
8 | const appContext = useContext(ComputerContext);
> 9 | const { products } = appContext;
| ^
10 | console.log(products);
11 |
12 | useEffect(() => {
render(<ComputerContext.Provider value={stuff}><Home /></ComputerContext.Provider>).