如何测试 React Beautiful DnD

问题描述 投票:0回答:2
After searching for examples on how to test react beautiful dnd I am still unable to get my tests to pass.
I am trying to simulate a drag and drop event and check that the table rows have been altered accordingly.

So I have a droppable table set up like this within my component :


```
<DragDropContext onDragEnd={handleDragEnd}>
                <Table sx={{ minWidth: 650,
                    borderCollapse: "separate",
                    borderSpacing: "0px 1rem" }}
                    aria-label="simple table">
                  <TableHead>
                    <TableRow>
                      {/* <TableCell sx={{color: "white", border: "0px solid"}}></TableCell> */}
                      <TableCell sx={{ color: "white", border: "0px solid" }}>ORDER</TableCell>
                      <TableCell sx={{ color: "white", border: "0px solid" }} align="center">TYPE</TableCell>
                      <TableCell sx={{ color: "white", border: "0px solid" }} align="left">CONTENT</TableCell>
                      <TableCell sx={{ color: "white", border: "0px solid" }} align="right">DELETE</TableCell>
                    </TableRow>
                  </TableHead>
                  <Droppable droppableId="droppable-1">
                    {(provider) => (
                      <TableBody
                        ref={provider.innerRef}
                        {...provider.droppableProps}>
                        {tableData()}
                        {provider.placeholder}
                      </TableBody>
                    )}
                  </Droppable>
                </Table>
              </DragDropContext>
```

Where the 'handleDragEnd' looks like this :


``` 
const handleDragEnd = (e) => {
    if (!e.destination) return;
    let tempData = Array.from(informationData);
    let [source_data] = tempData.splice(e.source.index, 1);
    tempData.splice(e.destination.index, 0, source_data);
    props.dispatch(setGeneralItem("informationData", tempData));
  };
```


The test, looks like this :



```
test("Drag and drop", ()=>{
  jest.mock('react-beautiful-dnd', () => ({
    Droppable: ({ children }) => children({
      draggableProps: {
        key:{},
        draggableId:{},
        index:{},
        style: {},
        onDragEnd: jest.fn(),
      },
      innerRef: jest.fn(),
    }, {}),
    Draggable:
      // params to children are `provider`, `snapshot`
      ({ children }) => children({
        draggableProps: {
          style: {},
        },
        innerRef: jest.fn(),
      }, {}),
    DragDropContext: ({ children }) => children,
  }));

  jest.spyOn(actions, "setGeneralItem");

  let info = [
    { order: 1, dataType: "Text", contentUrl: "some text" },
    { order: 2, dataType: "Image", contentUrl: "someimageurl" },
    { order: 3, dataType: "Video", contentUrl: "somevideourl" },
  ]
  let tempData = [
    { order: 1, dataType: "Image", contentUrl: "someimageurl" },
    { order: 2, dataType: "Video", contentUrl: "somevideourl" },
    { order: 3, dataType: "Text", contentUrl: "some text" },
  ]

  store.dispatch(actions.setGeneralItem("informationData", info))
  let mockDispatch = (val) => { store.dispatch(val); }
  const { container } = render(
    renderWithStore(store, <Information {...props} dispatch={mockDispatch}/>));

    let dragStart = container.querySelectorAll('tr')[1].querySelectorAll('td')[1]
  let dropPosition = container.querySelectorAll('tr')[3].querySelectorAll('td')[1]

  fireEvent.dragStart(dragStart)
  fireEvent.drop(dropPosition)
  expect(actions.setGeneralItem).toHaveBeenCalled();
  expect(actions.setGeneralItem).toHaveBeenCalledTimes(1);
  expect(actions.setGeneralItem).toHaveBeenCalledWith("informationData", tempData);
})
```






In the test, I am assigning the row to move as dragStart, the row where I would like to drop my target as dropPosition and I try to simulate the change with the react testing library events dragStart and drop. 

不幸的是,这个测试在最后一行失败了。最后一行检查表行是否已更改,但它仍然分派原始信息列表而不是 tempData。

fireEvent.dragStart 和 fireEvent.drop 似乎没有触发事件。我想知道如何使用react-beautiful-dnd模拟来模拟这个拖放事件。我不确定如何触发更改。

Does anyone have any idea how to actually fire this drag and drop event?

谢谢。

reactjs testing jestjs drag-and-drop
2个回答
6
投票

我已经设法不通过触发相应的事件而是使用键盘事件来模拟拖放。虽然不是最好的解决方案,但以下应该可以解决问题。

const SPACE = { keyCode: 32 };
const ARROW_DOWN = { keyCode: 40 };
fireEvent.keyDown(element, SPACE); // Begins the dnd
fireEvent.keyDown(element, ARROW_DOWN); // Moves the element
fireEvent.keyDown(element, SPACE); // Ends the dnd

0
投票

我正在使用react和enzyme进行测试...我嘲笑了react-beautiful-dnd这样的东西

`jest.mock('react-beautiful-dnd', () => ({
    Droppable: ({ children }) => children({
      draggableProps: {
    key:{},
    draggableId:{},
    index:{},
    style: {},
    onDragEnd: jest.fn(),
      },
      innerRef: jest.fn(),
    }, {}),
    Draggable:
      ({ children }) => children({
    draggableProps: {
      style: {},
    },
    innerRef: jest.fn(),
      }, {}),
    DragDropContext: ({ children }) => children,
  }));`

我的拖放中的内容是我想要测试的内容..但我没有得到它。我的组件如下:-

<Droppable droppableId="documentList"> {(provided) => ( <tbody  data-testid="table-body" {...provided.droppableProps} ref={provided.innerRef}> {formValue.fields && formValue.fields.map((field: any, index: number) => ( <Draggable key={index.toString()} draggableId={index.toString()} index={index}> {(provided) => ( <tr data-testid="table-body-row" key={index} ref={provided.innerRef} {...provided.draggableProps}>

我使用了 console.log("wrapperr",wrapper.debug());我得到了

   <DragDropContext onDragEnd={[Function: handleOnDragEnd]}> <Droppable droppableId="documentList"> [function] </Droppable> </DragDropContext>

因此我在这里遇到错误:-

  expect(wrapper.find({ "data-testid": "table-body" }).exists()).toBe(true); expect(wrapper.find({ "data-testid": "table-body-row" }).exists()).toBe(true);
对于两者我都得到错误的值 任何人都可以提供正确的方法,以便我可以测试我的内部内容??

© www.soinside.com 2019 - 2024. All rights reserved.