Search code examples
react-testing-library

react-testing-library - how to simulate file upload to a <input type="file" /> element?


I am using user-event to try to have more 'realistic' user interactions. However, after I click on the input, it will not fire the onChange function because by default it would only bring up the file explorer for the user to upload a file. How do I simulate the user uploading a file?

My code:

// Component
const FileInputComponent = ({ handleFileUpload }) => (
  <div>
    <input type="file" id="testing" accept=".png,.jpg" onChange={handleFileUpload} />
    <label htmlFor="testing">Input File Here</label>
  </div>
);
// Test file
test("Clicking on the label button calls the `handleFileUpload` function", () => {
  const handleFileUploadMockFn = jest.fn();
  const { getByLabelText } = render(<FileInputComponent handleFileUpload={handleFileUploadMockFn} />
  userEvent.click(getByLabelText("Input File Here"));
  expect(handleFileUploadMockFn).toHaveBeenCalledTimes(1);
});

Solution

  • Is the upload you want to test? https://github.com/testing-library/user-event

    I just write

    const fileInput = getByLabelText('file-input-label')
    userEvent.upload(fileInput, testFile)
    

    and it simulates the onChange for me.