javascript - 如何用 Jest 模拟 DataTransfer
问题描述
我有一些使用HTML 拖动界面的 React 组件。
特别是,我监听一个组件上的事件并使用DataTransfer对象dragover
设置 x 和 y 位置。然后,我监听不同组件上的事件并从 DataTransfer 中检索 x 和 y 位置。dragleave
我正在使用 Jest 和 Enzyme 来测试我的组件。
如果我运行测试,我会收到此错误:
Test suite failed to run
ReferenceError: DataTransfer is not defined
据我了解,Drag 接口在 Jest 中不可用,因此我需要模拟它并(也许?)通过Jest globals使其可用。
现在我DataTransfer
在 my 中定义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');
推荐阅读
- spring - Spring security + session:接收“Set-Cookie”标头但未在浏览器中设置
- javascript - 无法让单击事件侦听器在 svg 元素上工作
- java - 从包下的类中看不到外部 Jar
- java - 使用 Spring Data Couchbase 处理瞬态异常
- javascript - 两个日期之间的日历天数
- c++ - 如何在结构中使用 boost 库中的矩阵?
- reactjs - 让 HMR 在 chrome 扩展中使用 webpack/react
- azure-active-directory - 即使使用 O365 联合的 Yammer 身份验证弹出窗口
- javascript - 如何在运行时调用角度组件?
- php - 在 PHP 中获取基本 URL