12

Has anyone ever been able to test the drag-and-drop functionality from https://github.com/react-dnd/react-dnd using a functional component with useDrag and useDrop hooks?

According to the examples found here http://react-dnd.github.io/react-dnd/docs/testing, they either decorate the original component with a DragSource or a DropTarget HOC. For Example:

// ...

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)

Example taken from https://github.com/react-dnd/react-dnd/blob/master/packages/documentation/examples-decorators/src/01-dustbin/single-target/Box.tsx

I couldn't find any example of tests using their hooks though. They do have examples of code using both decorators and hooks (https://github.com/react-dnd/react-dnd/tree/master/packages/documentation) but there are examples of tests only using the decorators.

Jodevan
  • 732
  • 1
  • 6
  • 20

1 Answers1

1

I copied this from the github ticket and worked for me:

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);
});
Dharman
  • 30,962
  • 25
  • 85
  • 135
Julius Koronci
  • 408
  • 4
  • 10