【问题标题】:Tests using react-dnd with useDrag and useDrop使用 react-dnd 和 useDrag 和 useDrop 进行测试
【发布时间】:2020-01-19 12:30:21
【问题描述】:

有没有人能够使用带有 useDrag 和 useDrop 钩子的功能组件测试来自 https://github.com/react-dnd/react-dnd 的拖放功能?

根据在此处找到的示例http://react-dnd.github.io/react-dnd/docs/testing,它们要么使用 DragSource 或 DropTarget HOC 装饰原始组件。 例如:

// ...

export interface BoxProps {
    name: string

    // Collected Props
    isDragging: boolean
    connectDragSource: ConnectDragSource
}
const Box: React.FC<BoxProps> = ({ name, isDragging, connectDragSource }) => {
    const opacity = isDragging ? 0.4 : 1
    return (
        <div ref={connectDragSource} style={{ ...style, opacity }}>
            {name}
        </div>
    )
}

export default DragSource(
    ItemTypes.BOX,
    {
        beginDrag: (props: BoxProps) => ({ name: props.name }),
        endDrag(props: BoxProps, monitor: DragSourceMonitor) {
            const item = monitor.getItem()
            const dropResult = monitor.getDropResult()

            if (dropResult) {
                alert(`You dropped ${item.name} into ${dropResult.name}!`)
            }
        },
    },
    (connect: DragSourceConnector, monitor: DragSourceMonitor) => ({
        connectDragSource: connect.dragSource(),
        isDragging: monitor.isDragging(),
    }),
)(Box)

示例取自https://github.com/react-dnd/react-dnd/blob/master/packages/documentation/examples-decorators/src/01-dustbin/single-target/Box.tsx

我找不到任何使用他们的钩子进行测试的例子。他们确实有使用装饰器和挂钩的代码示例 (https://github.com/react-dnd/react-dnd/tree/master/packages/documentation),但也有仅使用装饰器的测试示例。

【问题讨论】:

标签: reactjs react-dnd


【解决方案1】:

我从 github 票上复制了这个并为我工作:

const dragAndDrop = (src: Element, dst: Element) => {
  fireEvent.dragStart(src);
  fireEvent.dragEnter(dst);
  fireEvent.drop(dst);
  fireEvent.dragLeave(dst);
  fireEvent.dragEnd(src);
 };
const allSections = rendered.getAllByRole('dropzone');

const marketSection = allSections[0];
const marketExpandedSection = allSections[1];

const basisIdDrag = within(marketSection).getByRole('draggable');

act(() => {
  dragAndDrop(basisIdDrag, marketExpandedSection);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-07-26
    • 2023-02-16
    • 2022-06-16
    • 2021-12-26
    • 2018-12-11
    • 2017-02-25
    • 1970-01-01
    • 2022-11-24
    相关资源
    最近更新 更多