我使用React Dnd(與鼠標後端)拖動項目,它的工作就像一個魅力。 但是我可能有,我希望能夠測試用例:是React dnd從外部拖動項目拖動狀態可訪問
monitor.isDragging()
從源和目標組件外,要知道,如果有一個當前拖動操作。
我使用React Dnd(與鼠標後端)拖動項目,它的工作就像一個魅力。 但是我可能有,我希望能夠測試用例:是React dnd從外部拖動項目拖動狀態可訪問
monitor.isDragging()
從源和目標組件外,要知道,如果有一個當前拖動操作。
從你的問題來看,目前還不清楚你現在是否能夠在DragSource/DropTarget中測試monitor.isDragging(),所以我會先假設你不知道該怎麼做。
首先,任何包裝在DragSource/DropTarget中的組件都不能在拖放上下文之外進行渲染,因此您必須確保在虛擬拖放上下文中渲染組件(代碼部分複製在從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 />);
});
一旦你渲染您的組件這樣,你現在可以訪問監控器像這樣(的getMonitor()函數不是在文檔中,但它的那裏和你期望的作品):
const manager = RenderedComponent.get(0).getManager();
const monitor = manager.getMonitor();
因此,您現在可以訪問monitor.isDragging()
(注isDragging:如果您的使用案例包括設置isDragging爲true,然後再檢查,如果一個類被渲染也可以存根這些監控功能或者其他的東西)。
從源或應該那麼該組件的測試中被要求目標組件的測試中,所有的外部檢查它是一樣的東西:
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;