5

I'm trying to test my implementation of react-dnd, and in one of my drop functions I'm using the monitor.getInitialClientOffset() function to get an offset, and I'd like to stub this method to return a particular offset that I can then assert on, but I cannot figure this out. In my test I'm using

const WrappedContext = wrapInTestContext(ContextArea);
const page = mount(<WrappedContext />);
const manager = page.get(0).getManager();
const backend = manager.getBackend();

// Couple finds to get the right source and target ids

backend.simulateBeginDrag([sourceId])
backend.simulateHover([targetId])
backend.simulateDrop();
backend.simulateEndDrag();

(This is using the standard wrapInTestContext from https://gaearon.github.io/react-dnd/docs-testing.html)

The drop function is passed a monitor from the test backend and I don't see a way in the documentation to pass a stubbed version of it to any of the simulation methods.

Ben Hare
  • 4,365
  • 5
  • 27
  • 44

1 Answers1

5

So it turns out that you can access the monitor that the test backend is using and then stub out methods on it like this:

  const manager = page.get(0).getManager();
  const backend = manager.getBackend();
  const monitor = manager.getMonitor();

  sinon.stub(monitor, 'getInitialClientOffset', () => {
    return {
      x: 10,
      y: 20,
    };
  });

  sinon.stub(monitor, 'getDifferenceFromInitialOffset', () => {
    return {
      x: 2,
      y: 4,
    };
  });

And then in the drop function those are the values that will be used in any sort of math you're using.

Ben Hare
  • 4,365
  • 5
  • 27
  • 44