我有一些使用 HTML Drag interface 的 React 组件.
特别是我听dragover
一个组件上的事件并使用 DataTransfer 设置 x 和 y 位置目的。然后,我听dragleave
不同组件上的事件并从 DataTransfer 检索 x 和 y 位置。
我正在使用 Jest 和 Enzyme 来测试我的组件。
如果我运行测试,我会收到此错误:
Test suite failed to run
ReferenceError: DataTransfer is not defined
据我了解,Jest 中没有 Drag 界面,所以我需要模拟它并(也许?)通过 Jest globals 使其可用.
现在我定义了
DataTransfer
在我的jest.config.js
并使其成为全局性的,但我不确定这是否是最佳解决方案。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;
在 Jest 中模拟 Drag 界面的最佳方法是什么?
最佳答案
我正在使用以下自定义模型:
// Arrange
// Map as storage place
const testStorage = new Map();
// Mock of the drop Event
const testEvent = {
dataTransfer: {
setData: (key, value) => testStorage.set(key, value),
getData: (key) => testStorage.get(key)
}
};
// remmeber to have 'and.callTrough()' to allow go trough the method
spyOn(testEvent.dataTransfer, 'getData').and.callThrough();
// Act
// Add your code here
// Assert
expect(testEvent.dataTransfer.getData('YOUR_CHECKED_KEY')).toEqual('EXCPECTED_VALUE');
关于javascript - 如何用 Jest 模拟 DataTransfer,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54864280/