5

I am working on implementing "drag and drop" using react-dnd. This involves dragging an item from one component and dropping it into another component. Functionally, it works great, but I am having trouble testing the "drop" so that the function gets triggered. When I test, I cannot get it to register that I'm dropping at all.

Some pertinent info:

  • This is a functional component - most documentation is centered around class components
  • Most documentation I have seen involves dragging and dropping within the same component - this is happening between two separate components
  • I have tried testing with both enzyme (using mount) and the React testing library (using render)

"Drop" component code

const TableBody = React.forwardRef(({ <props> }: Props, ref) => {
    const [{ isOver }, drop] = useDrop({
        accept: 'TestItem',
        drop: (droppedItem: any) => dropFunction(droppedItem),
        collect: monitor => ({
            isOver: monitor.isOver(),
        }),
    });

    ...

    return (
        <MaterialTableBody ref={ref} role='rowgroup'>
            { <code to render rows }
        </MaterialTableBody>
    );
});

Example test

test('Dropping on a table triggers the drop function', () => {
    const mockDropFunction = jest.fn();
    const NewContext = wrapInTestContext(TableBody);
    render(
        <NewContext <props> dropFunction={mockDropFunction} />
    );
    
    const tables = screen.getAllByRole('rowgroup');
    const table = tables[0];
    const mockDroppedItem = { id: 'test', type: 'TestItem' };

    fireEvent.drop(table, {
        dataTransfer: mockDroppedItem,
    });

    expect(mockDropFunction).toHaveBeenCalled();
});

I've tried some different iterations, such as firing an event for each step (dragStart, dragEnter, dragOver, drop), and a few other things. But I can't get anything to even happen. What is the best way to mock something being "droppped" in a functional component?

0 Answers0