I am writing unit tests for a drag and drop interaction that relies on the dataTransfer
of the event. Also I am using typescript. To simulate the event(s) I wrote this little function:
function createDragEvent(eventName: string, dataTransferData?: Array<any>) {
const event = new CustomEvent(eventName, { bubbles: true, cancelable: true });
event.dataTransfer = {
setData: jasmine.createSpy("setData() spy"),
getData: jasmine.createSpy("getData() spy").and.callFake(function() {
return dataTransferData[0] === 'text/plain' ? dataTransferData[1] : undefined;
})
};
return event;
}
However, TypeScript tells me
TS2339: Property 'dataTransfer' does not exist on type 'CustomEvent'.
I cannot not use the dataTransfer
and I cannot use native DragEvent
s because I cannot set the data or spy on its functions. Is there a way to deal with this, e.g. tell TypeScript that dataTransfer
is ok or disable the error for this file or something like that?
If anyone comes here like I did because the Event
object in TypeScript does not have a dataTransfer
attribute:
Just use DragEvent
instead.
Could you do something like this?
const event: CustomEvent & { dataTransfer?: DataTransfer } =
new CustomEvent(eventName, { bubbles: true, cancelable: true });
If you are like me and cannot use the CustomEvent
solution because your function is expecting a DragEvent
the following worked for me:
const dragEvent = new DragEvent('test')
const mockEvent = {
...dragEvent,
dataTransfer: new DataTransfer()
} as DragEvent
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With