首页 > 解决方案 > 如何用 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 界面的最佳方法是什么?

标签: javascriptreactjsunit-testingjestjsdrag

解决方案


我正在使用以下自定义模型:

  // 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');


推荐阅读