Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stub the monitor while testing react-dnd?

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.

like image 365
Ben Hare Avatar asked Jul 07 '16 19:07

Ben Hare


1 Answers

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.

like image 168
Ben Hare Avatar answered Oct 31 '22 18:10

Ben Hare