Mocking file input in React TestUtils
Do you need a 'true' file? I think your issue is in how you're managing your 'fake' file, and your file input's change event. You can use the File Api to 'create' a dummy file, and then you just have to properly set your file input. It doesn't use value
, but rather files
.
// similar example from KCD https://github.com/testing-library/react-testing-library/issues/93#issuecomment-392126991const file = new File(['(⌐□_□)'], 'chucknorris.png', { type: 'image/png' });TestUtils.Simulate.change(fileInput, { target: { files: [ file ] } });
If you actually needed the 'file' (upload_text.txt), then that could be more tricky. Node fs.readFile
is async, and the data isn't available outside of the callback
, plus you'd have to convert the data
into an actual file object to give to the input.
// rough pass at this, you'll have to play with itimport fs from 'fs';const filename = 'upload_text.txt';fs.readFile(filename, 'utf8', (err, data) => { if (err) throw err; const file = new File(data, filename, { type: 'text/plain' }); TestUtils.Simulate.change(fileInput, { target: { files: [ file ] } }); // whatever comes next});