react-dnd / react-dnd

Drag and Drop for React
http://react-dnd.github.io/react-dnd
MIT License
20.91k stars 1.99k forks source link

Cannot write a unit test to make sure that it is not possible to drag some draggable #3624

Open Nokel81 opened 5 months ago

Nokel81 commented 5 months ago

Describe the bug I am trying to write a unit test to verify that some useDrag cannot be dragged under some conditions however the way that I have found to test throws an Invariant Violation: Cannot call hover while not dragging. error.

Reproduction

This is how I do the test

const firstItem = discover.getSingleElement("slot-index", "1").discovered; // This item has `canDrag: false`
const secondItem = discover.getSingleElement("hotbar-item-id", "some-id").discovered;

fireEvent.dragStart(firstItem);
fireEvent.dragEnter(secondItem);
fireEvent.dragOver(secondItem);
fireEvent.drop(firstItem);

Expected behavior Nothing to been thrown but also not calls drop.

Nokel81 commented 5 months ago

FYI I have found a workaround for the time being

import type { Backend, BackendFactory } from "dnd-core";
import { HTML5Backend } from "react-dnd-html5-backend";

const HotbarBackend: BackendFactory = (manager, globalContext, configuration) => {
  const base = HTML5Backend(manager, globalContext, configuration) as Backend & {
    handleTopDrop: (e: DragEvent) => void;
  };
  const internalHandleTopDrop = base.handleTopDrop;

  base.handleTopDrop = (e: DragEvent) => {
    try {
      internalHandleTopDrop(e);
    } catch (error) {
      if (process.env.JEST_WORKER_ID) {
        if (process.env.DEBUG) {
          console.warn(error);
        }
      } else {
        throw error;
      }
    }
  };

  return base;
};