React Beautiful DND单元测试报错:找不到所需上下文
解决react-beautiful-dnd单元测试中"Could not find required context"报错
以下是几个常见的排查方向和解决办法:
确认DragDropContext的正确包裹方式
react-beautiful-dnd的Draggable和Droppable组件必须被DragDropContext直接或间接包裹,且DragDropContext必须传入必填的onDragEnd回调(哪怕是空函数)。测试代码里要确保整个包含拖拽组件的树都在这个上下文内,示例代码:import { render } from '@testing-library/react'; import { DragDropContext } from 'react-beautiful-dnd'; import YourDraggableComponent from './YourDraggableComponent'; test('renders draggable items without context error', () => { render( <DragDropContext onDragEnd={() => {}}> <YourDraggableComponent /> </DragDropContext> ); // 你的断言逻辑 });避免使用浅层渲染
如果用Enzyme的shallow方法渲染组件,它不会完整传递上下文到嵌套的Draggable/Droppable组件,直接导致找不到上下文的报错。改用mount方法或者react-testing-library的render(全渲染)即可解决:import { mount } from 'enzyme'; import { DragDropContext } from 'react-beautiful-dnd'; test('mounts component with valid drag context', () => { const wrapper = mount( <DragDropContext onDragEnd={() => {}}> <YourDraggableComponent /> </DragDropContext> ); // 你的断言逻辑 });模拟测试环境缺失的API
react-beautiful-dnd依赖浏览器的requestAnimationFrameAPI,部分测试环境(如Jest默认配置)没有内置这个模拟,可能间接引发上下文相关报错。在测试的setup文件中添加以下模拟代码:global.requestAnimationFrame = (callback) => { setTimeout(callback, 0); };检查组件的条件渲染逻辑
如果你的组件内部有条件渲染拖拽元素的逻辑(比如仅在某个状态或props满足时渲染Draggable),测试时要确保这些条件被触发,避免部分拖拽组件脱离DragDropContext的包裹范围。
内容的提问来源于stack exchange,提问作者Abhinandan Kushwaha
相关产品推荐
相关产品推荐

