I have a component in React that uses react-beautiful-dnd. This component renders a list of items that can be dragged. Here is the code for this component-
const LeftPanelForTables = (props: LeftPanelForTablesProps) => {
const { items } = props;
return items.map((item: any, index: number) => (
<Draggable
key={item.id}
draggableId={item.id}
index={index}
>
{(provided, snapshot) => (
<div
className={cx(styles.table)}
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<div className={cx(styles.table_parent)}>
<Typography
variant={'p'}
className={styles.tableText}
>
{item.name}
</Typography>
</div>
</div>
)}
</Draggable>
));
};
export default LeftPanelForTables;
This code runs properly without any error and produces the desired output.
Now I am writing a unit test for this code.
describe('LeftPanelForTables', () => {
const items = [
{ id: '1', name: 'Table 1', isSelected: false },
{ id: '2', name: 'Table 2', isSelected: true },
];
it('renders the table items correctly', () => {
const { container, getByText } = render(
<DragDropContext onDragEnd={(result:DropResult)=>{}}>
<LeftPanelForTables items={items} />
</DragDropContext>
);
// Check if both table names are rendered
expect(getByText('Table 1')).toBeInTheDocument();
expect(getByText('Table 2')).toBeInTheDocument();
});
});
The test fails with below error-
Error: Uncaught [Error: Error: Uncaught RbdInvariant {
message: ‘Invariant failed: Could not find required context’
}
2
Answers
In my test file, I had to wrap the
<LeftPanelForTables>
component within<Droppable>
imported from react-beautiful-dnd.Here is a gif that explains the component hierarchy in react-beautiful-dnd-
In my code, since the
<LeftPanelForTables>
contains a<Draggable>
, we need to wrap it inside a<Droppable>
and the<Droppable>
should be wrapped inside<DragDropContext>
.So here is my new test file-
try wrapping your component with the
DragDropContextProvider
fromreact-beautiful-dnd
.Make sure to import
DragDropContextProvider