peterh32 / react-drag-drop-container

ReactJS drag and drop functionality for mouse and touch devices
MIT License
154 stars 47 forks source link

Problems writing unit tests #58

Closed maestrokame closed 3 years ago

maestrokame commented 3 years ago

Hi, awesome component. It works like a charm. 🙆‍♂️

Though, I'm having a hard time trying to write a working test for the drag-and-drop part using Jest and Testing-Library.

Did some of you guys managed to write a unit test?

maestrokame commented 3 years ago

I'm not proud of this but, because of jdom limitation, this is what I ended up doing.

const incorrectItems = document.querySelectorAll("[data-testid=incorrectBox] .ddcontainersource [data-testid=draggableItem]")
const primaryBox = document.querySelector("[data-testid=primaryBox]")

window.getSelection = jest.fn()
window.getSelection.mockReturnValue({removeAllRanges: jest.fn()})
document.elementFromPoint = jest.fn()
document.elementFromPoint.mockReturnValue(primaryBox)

const primaryItemsBefore = document.querySelectorAll("[data-testid=primaryBox] .ddcontainersource [data-testid=draggableItem]")
expect(primaryItemsBefore).toHaveLength(0)

fireEvent.mouseDown(incorrectItems[0].parentElement, {button: 1})
fireEvent.mouseMove(incorrectItems[0].parentElement)
fireEvent.mouseUp(primaryBox)

const primaryItemsAfter = document.querySelectorAll("[data-testid=primaryBox] .ddcontainersource [data-testid=draggableItem]")
expect(primaryItemsAfter).toHaveLength(1)
expect(primaryItemsAfter[0]).toHaveTextContent('Jorge')