javascript - 如何用 Jest 模拟 DataTransfer

标签 javascript reactjs unit-testing jestjs drag

我有一些使用 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/

相关文章:

javascript - 删除输出中的 %20

javascript - 通过 id 隐藏 block

node.js - 语法错误: Unexpected end of JSON input while parsing near '…: {"name":"@babel/plug' ?

c++ - 如何通过 gcc/g++ 或 clang 构建和使用 googletest (gtest) 和 googlemock (gmock)?

javascript - 为什么 Sequelize 只使用 findAll() 返回一个对象?

javascript - 你能在失去焦点时阻止 jQuery focusout 触发吗?

javascript - 我似乎无法使用react将这些方法传递给我的组件

reactjs - 如何从react-router中的url中删除哈希值

javascript - 模拟 Angular 模型的 $http.put 结果 - 单元测试

c# - 我可以在 Moq 中重用 It.Any 参数描述符吗