React大型Canvas组件测试咨询:对象移动与新增功能测试
React 类 Figma Canvas 核心功能测试方案
一、对象移动功能测试
1. 单元测试(聚焦逻辑层)
如果你的移动逻辑基于状态管理(比如useState、Redux)维护对象坐标,直接测试状态更新逻辑:
- 模拟鼠标事件核心参数:编写测试用例,传入
mousedown初始坐标、mousemove偏移量,断言对象的x/y属性是否按预期更新。 - 示例代码:
test('移动对象时坐标正确更新', () => { const initialShape = { id: '1', x: 50, y: 50, width: 100, height: 100 }; const updatedShape = handleShapeMove(initialShape, { dx: 30, dy: 40 }); expect(updatedShape.x).toBe(80); expect(updatedShape.y).toBe(90); });
- 额外测试边界场景:如果有Canvas边缘限制逻辑,断言移动后的坐标不会超出Canvas范围。
2. 集成测试(模拟真实用户操作)
用Testing Library或Cypress模拟完整交互流程:
- 步骤:定位Canvas元素 → 模拟
mousedown在目标对象区域 → 模拟mousemove到指定位置 → 触发mouseup→ 校验对象最终坐标。 - 示例(Testing Library):
test('用户拖拽对象后坐标正确', async () => { render(<Canvas />); const canvas = screen.getByTestId('figma-like-canvas'); // 模拟拖拽:按下→移动→松开 fireEvent.mouseDown(canvas, { clientX: 50, clientY: 50 }); fireEvent.mouseMove(canvas, { clientX: 80, clientY: 90 }); fireEvent.mouseUp(canvas); // 从状态或DOM获取对象数据断言 const movedShape = getShapeFromState('1'); expect(movedShape.x).toBe(80); expect(movedShape.y).toBe(90); });
二、Canvas对象新增的属性检测
1. 单元测试(验证对象创建逻辑)
如果有创建对象的核心函数,直接测试其返回值的属性:
- 示例代码:
test('创建矩形对象时属性正确', () => { const newShape = createRectangle({ x: 100, y: 100, width: 200, color: '#ff0000' }); expect(newShape.x).toBe(100); expect(newShape.y).toBe(100); expect(newShape.width).toBe(200); expect(newShape.color).toBe('#ff0000'); });
2. 集成测试(验证用户操作后的结果)
分两种场景处理:
场景1:对象是DOM元素(比如用div模拟图形)
- 模拟用户新增操作(点击工具栏按钮+拖拽Canvas),通过
data-testid定位新增对象,校验DOM属性:
test('新增矩形后属性符合预期', async () => { render(<Canvas />); // 点击创建矩形按钮 fireEvent.click(screen.getByTestId('create-rect-btn')); // 在Canvas上拖拽绘制 const canvas = screen.getByTestId('figma-like-canvas'); fireEvent.mouseDown(canvas, { clientX: 100, clientY: 100 }); fireEvent.mouseMove(canvas, { clientX: 300, clientY: 200 }); fireEvent.mouseUp(canvas); // 定位新增的矩形 const newRect = screen.getByTestId('shape-2'); expect(newRect.offsetLeft).toBe(100); expect(newRect.offsetTop).toBe(100); expect(newRect.offsetWidth).toBe(200); expect(newRect.style.backgroundColor).toBe('rgb(255, 0, 0)'); // 对应#ff0000 });
场景2:Canvas 2D上下文绘制的图形
- 由于是像素级绘制,无法直接通过DOM获取属性,需依赖维护的绘制对象数组断言:
test('Canvas 2D新增图形属性正确', async () => { render(<Canvas />); // 模拟创建图形操作 fireEvent.click(screen.getByTestId('create-circle-btn')); fireEvent.mouseDown(screen.getByTestId('figma-like-canvas'), { clientX: 150, clientY: 150 }); fireEvent.mouseUp(screen.getByTestId('figma-like-canvas'), { clientX: 250, clientY: 250 }); // 从状态中获取绘制对象列表 const shapes = getAllShapesFromState(); const newCircle = shapes.find(s => s.id === '3'); expect(newCircle.x).toBe(150); expect(newCircle.y).toBe(150); expect(newCircle.radius).toBe(100); expect(newCircle.color).toBe('#00ff00'); });
- 若需验证视觉效果,可使用截图对比工具(如Cypress的
snapshot),确保新增图形的颜色、尺寸与预期一致。
内容的提问来源于stack exchange,提问作者Ilya
相关产品推荐
相关产品推荐

