I have some React components where I use the HTML Drag interface.
In particular, I listen to dragover
events on one component and set x and y positions with the DataTransfer object. Then, I listen to dragleave
events on a different component and retrieve x and y positions from the DataTransfer.
I'm using Jest and Enzyme to test my components.
If I run my tests I get this error:
Test suite failed to run
ReferenceError: DataTransfer is not defined
As far I understand, the Drag interface is not available in Jest, so I need to mock it and (maybe?) make it available via Jest globals.
For now I defined DataTransfer
in my jest.config.js
and made it a global, but I'm not sure if this is the best solution.
class DataTransfer {
constructor() {
this.data = { dragX: "", dragY: "" };
this.dropEffect = "none";
this.effectAllowed = "all";
this.files = [];
this.img = "";
this.items = [];
this.types = [];
this.xOffset = 0;
this.yOffset = 0;
}
clearData() {
this.data = {};
}
getData(format) {
return this.data[format];
}
setData(format, data) {
this.data[format] = data;
}
setDragImage(img, xOffset, yOffset) {
this.img = img;
this.xOffset = xOffset;
this.yOffset = yOffset;
}
}
const baseConfig = {
globals: {
DataTransfer: DataTransfer,
},
// other config...
};
module.exports = baseConfig;
What is the best way to mock the Drag interface in Jest?
dataTransfer
object or theDataTransfer
object? – Contribution