Search code examples
javascriptreactjsunit-testingjestjstesting-library

How do I mock a DataTransfer item for testing-library


I am trying to use Testing-library user-event paste to test an onPaste event handler for a react component.

The event handler:

pasteHandler = (event: any) => {
    const text = event.clipboardData.getData("text");
    parseAndUpdateState(text);
}

If I try const clipboardData = new DataTransfer(); or a global mock as mentioned here I get: Error: Uncaught [ReferenceError: DataTransfer is not defined].

No matter how I try to define either a mock jest object or create my own definition, I get errors for either missing dataTransfer object or missing fields.

Is there a something I am missing for how to mock out a DataTransfer object where I just need to get clipboard data?


Solution

  • Found Article from Question

    I missed the documentation for createEvent and after using that along with

      const PhoneNumberElement = screen.queryByTestId('paste-input');
    
      const paste = createEvent.paste(PhoneNumberElement, {
        clipboardData: {
          getData: () => '123456',
        },
      });
    
      fireEvent(PhoneNumberElement, paste);
    

    as mentioned in the article I was able to paste and trigger the onPaste handler.