All of my components get data and methods from the Context. I want to test -at least- "component renders" case but of course, when I try to render component in a test case, it cannot find methods/functions and data that come from the Context. I couldn't find a way to pass Context values to a test case using React Testing Library or Jest (I need to use these libraries, no enzyme)
Let's say I want to test a simple Filter component.
Context (primitive usage I guess)
import { useState, useEffect, createContext } from "react";
const Context = createContext();
const ContextProvider = ({ children }) => {
const [books, setBooks] = useState([]);
// other data and method code..
const handleFilter = (value) => {
const filteredBooks = [...books];
if (books.length > 0) {
switch (value) {
case "alphabetical":
filteredBooks.sort((a, b) => a.title - b.title);
setBooks(filteredBooks);
break;
case "publishdate":
filteredBooks.sort(
(a, b) => b.first_publish_year - a.first_publish_year
);
setBooks(filteredBooks);
break;
default:
setBooks(filteredBooks);
}
}
};
return (
<Context.Provider value={{ handleFilter }}>
{children}
</Context.Provider>
);
};
export { ContextProvider, Context };
Filter
import { useContext } from "react";
import { Context } from "../context/Context";
function Filter() {
const { handleFilter } = useContext(Context);
return (
<div className="filter" data-testid="filter-test">
<div className="filter-content">
<select
defaultValue="none"
className="filter-btn"
onChange={(e) => handleFilter(e.target.value)}
>
<option value="none" defaultValue disabled>
Filter Results
</option>
<option value="alphabetical">Alphabetically</option>
<option value="publishdate">Publish Date (newest)</option>
</select>
</div>
</div>
);
}
export default Filter;
Filter.test.js
import { render, screen, cleanup } from '@testing-library/react';
import Filter from './Filter';
test('renders Filter component without crashing', () => {
// I need to pass handleFilter function using Context somehow
render(<Filter />);
const filterComponent = screen.getByTestId('filter-test');
expect(filterComponent).toBeInTheDocument();
});
If you want to see all code: https://codesandbox.io/s/inspiring-bhaskara-0s98g