a day ago

Is the file empty when using React testing-library to test file (pdf) uploads?

As a senior JavaScript developer, I am currently testing file upload with react-testing-library. However, I am facing an issue where the log shows an empty file, despite it being functional on the browser. After extensive research, I have discovered that since tests run on node .js, the File object lacks some properties (all) and ultimately displays as:
File {}
To provide context, below is the applicable code:
const file = new File(['hello'], 'hello.pdf', {type: 'application/pdf'})
const input = screen.getByTestId('attachment-input')
await userEvent.upload(input, file)
Although I have attempted to install blob polyfill and switch File to Blob, encountering errors has hindered my progress.
a day ago
Verified Answer
The issue you are facing is because the File object is not fully supported in Node.js environment. One workaround to test file upload with react-testing-library is to mock the file input and its properties using FormData. Here's an example code snippet:
const file = new File(['hello'], 'hello.pdf', { type: 'application/pdf' });
const data = new FormData();
data.append('attachment', file);

const input = screen.getByTestId('attachment-input');
Object.defineProperty(input, 'files', {
  value: data.get('attachment'),

await fireEvent.change(input);
In this code snippet, we create a FormData object and append the File object to it. Then, we get the file input element using getByTestId, and set the files property of the input element to the File object using Object.defineProperty. Finally, we simulate a change event on the file input element using fireEvent.change. This should trigger the file upload function and you can test the rest of your code accordingly.