0

I'm using React Dnd (with mouse backend) for dragging items and it's working like a charm. However I may have a use case where I want to be able to test:

monitor.isDragging()

From outside the Source and Target components, to know if there's a current dragging operation.

Ben Hare
  • 4,365
  • 5
  • 27
  • 44
Sami Jmii
  • 460
  • 7
  • 17

1 Answers1

0

From your question it's not clear if you're currently able to test monitor.isDragging() from within a DragSource/DropTarget already, so I'll start off assuming you don't know how to do that.

First of all, any component that is wrapped in a DragSource/DropTarget cannot be rendered outside of a Drag and Drop Context, so you have to make sure to render your component within a fake Drag and Drop Context (code partially copied over from https://react-dnd.github.io/react-dnd/docs-testing.html)

import React, { Component } from 'react';
import TestBackend from 'react-dnd-test-backend';
import { DragDropContext } from 'react-dnd';
import { mount } from 'enzyme';

/**
 * Wraps a component into a DragDropContext that uses the TestBackend.
 */
function wrapInTestContext(DecoratedComponent) {
  return DragDropContext(TestBackend)(
    class TestContextContainer extends Component {
      render() {
        return <DecoratedComponent {...this.props} />;
      }
    }
  );
}

it('can be tested with the testing backend', () => {
  const WrappedComponent = wrapInTestContext(MyComponent);

  const RenderedComponent = mount(<WrappedComponent />);
});

Once you've rendered your component like this, you can now access the monitor like this (the getMonitor() function isn't in the documentation, but it's there and works like you'd expect):

const manager = RenderedComponent.get(0).getManager();

const monitor = manager.getMonitor();

Therefore, you can now access isDragging with monitor.isDragging() (Note: You can also stub these monitor functions if your use case involves setting isDragging to true and then later checking if a class is rendered or something).

To check it from outside a Source or Target component's tests, all that should then be required inside of that components tests is something like:

const WrappedDragComponent = wrapInTestContext(MyDragComponent);
const page = mount(<WrappedDragComponent />);
const manager = page.get(0).getManager();
const backend = manager.getBackend();
const monitor = manager.getMonitor();
        
const dragSourceId = page.find(MyDragComponent).get(0).getHandlerId();

backend.simulateBeginDrag([dragSourceId]);
        
expect(monitor.isDragging()).to.be.true;
Ben Hare
  • 4,365
  • 5
  • 27
  • 44