我在React中有一个使用react-beautiful-dnd的组件。该组件呈现可拖动的项目列表。这是该组件的代码-
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;
此代码运行正常,没有任何错误,并产生所需的输出。
现在我正在为这段代码编写单元测试。
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();
});
});
测试失败并出现以下错误 -
错误:未捕获[错误:错误:未捕获RbdInvariant {
消息:“不变失败:找不到所需的上下文”
}
在我的测试文件中,我必须将
<LeftPanelForTables>
组件包装在从react-beautiful-dnd 导入的 <Droppable>
中。在我的代码中,由于
<LeftPanelForTables>
包含 <Draggable>
,我们需要将其包装在 <Droppable>
内,并且 <Droppable>
应包装在 <DragDropContext>
内。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)=>{}}>
<Droppable droppableId="droppable" isDropDisabled={true}>
{(provided: any, snapshot: any) => (
<div ref={provided.innerRef}>
<LeftPanelForTables items={items} />
</div>
)}
</Droppable>
</DragDropContext>
);
// Check if both table names are rendered
expect(getByText('Table 1')).toBeInTheDocument();
expect(getByText('Table 2')).toBeInTheDocument();
});
});
谢谢你。为我工作。
我猜你的组件中需要一个盒子包装器,因为没有他就会出现警告。
警告:遇到设置问题。
> Invariant failed:
provided.innerRef has not been provided with a HTMLElement.
所以,我使用这个最终代码:
const { getByText } = render(
<DragDropContext onDragEnd={(result: DropResult) => console.log(result)}>
<Droppable droppableId="droppable-test" isDropDisabled>
{(provided: DroppableProvided) => (
<Box ref={provided.innerRef} {...provided.droppableProps}>
<TaskCard
cards={card}
/>
</Box>
)}
</Droppable>
,
</DragDropContext>,
);