How to test 'paste' event in a generic input text with React Testing Library

Viewed 2055

I am trying to test in "integration" a pasting functionality using rect testing library. So far, I have been able to trigger the 'paste' event, and see the paste event being passed to the onPaste prop of my input field.

The thing I'd like to test is the actual value of the element being changed into whatever is being pasted. Follows the example:


import { TextField } from '@material-ui/core';

it('should show an empty cell if value is incorrect', async () => {
  const { getByDisplayValue } = await render(
    <TextField
      value=""
      onPaste={event => {
        console.log(event.clipboardData.getData('text'));
      }}
      onChange={e => {
        console.log(e.currentTarget.value);
      }}
    />
  );

  const input = await getByDisplayValue('');

  const eventProperties = {
    clipboardData: {
      getData: jest.fn().mockReturnValueOnce('Foo Bar Test'),
    },
  };
  const pasteEvent = createEvent.paste(input, eventProperties);
  pasteEvent.clipboardData = eventProperties.clipboardData;

  fireEvent(input, pasteEvent);

  await waitFor(() => {
    getByDisplayValue('Foo Bar Test');
  });
});

As a result, I get:

console.log MyComponent.test.js:110
    Foo Bar Test


TestingLibraryElementError: Unable to find an element with the display value: Foo Bar Test.

<body>
  <div>
    <div
      class="MuiFormControl-root MuiTextField-root"
    >
      <div
        class="MuiInputBase-root MuiInput-root MuiInput-underline MuiInputBase-formControl MuiInput-formControl"
      >
        <input
          aria-invalid="false"
          class="MuiInputBase-input MuiInput-input"
          type="text"
          value=""
        />
      </div>
    </div>
  </div>
</body>

I would expect the value prop of the TextField being populated with the content of the pasting event, but as you can see, it is empty. Also, I would expect the onChange event to be triggered, but this is not the case either (no console log in the test is showed).

0 Answers
Related