admin管理员组

文章数量:1315979

I made a custom hook, useFileListState, that basically encapsulates the logic to add and remove files from a FileList.

To remove (or add) it, it uses the DataTransfer constructor, as well as the property files and the method items.add():

function deleteFile(fileToDelete: File) {
  setData((prevData) => {
    if (!prevData) return null;

    const fileToDeleteId = getFileToken(fileToDelete);
    const dt = new DataTransfer();

    for (let i = 0; i < prevData.length; i++) {
      const file = prevData[i];
      const id = getFileToken(file);
      if (id !== fileToDeleteId) dt.items.add(file);
    }
   return dt.files;
  });
}

The problem is, Jest doesn't recognize the DataTransfer constructor, so I need to mock it somehow, which I tried to do this way:

class mockDataTransfer {
  files: File[] = [];
  items = {
    add: (file: File) => {
      this.files.push(file);
    },
  };
}

jest.spyOn(global, "DataTransfer").mockImplementation(() => mockDataTransfer as unknown as DataTransfer);

But this fails because Property 'DataTransfer' does not exist in the provided object.

Can someone help me mocking the DataTransfer constructor?

本文标签: javascriptHow to mock DataTransfer constructor in JestStack Overflow