Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate dataTransfer for drag events in TypeScript

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 DragEvents 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?

like image 948
Lukas Avatar asked Feb 23 '17 15:02

Lukas


3 Answers

If anyone comes here like I did because the Event object in TypeScript does not have a dataTransfer attribute:

Just use DragEvent instead.

like image 117
Michael Bolli Avatar answered Jan 10 '23 18:01

Michael Bolli


Could you do something like this?

const event: CustomEvent & { dataTransfer?: DataTransfer } =
    new CustomEvent(eventName, { bubbles: true, cancelable: true });
like image 39
libertyernie Avatar answered Jan 10 '23 18:01

libertyernie


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
like image 31
golkedj Avatar answered Jan 10 '23 17:01

golkedj