javascripthtmltestingreactjsreactjs-testutils

How to set HTML5 file type input with ReactTestUtils


I have an HTML5 file type input in a React form similar to the following

<input type='file' ref='fileInput' onChange={this.onChange} multiple/>

and once a file is uploaded this.onChange accesses the selected files, validates them and transitions the form.

I'm trying to figure out how to test this functionality using ReactTestUtils.Simulate but cant figure out how to set the files that should be sent to the onChange callback in event.currentTarget.files.

Can anybody help guide me in the right direction to how I can mock/test this effectively?


Solution

  • Found out that before TestUtils.Simulate.change is called the files need to be set on the object explicitly. Something similar to the following should work.

    It's ES6 adapted from Coffeescript so I'm not sure if it is exactly correct syntax.

    // Needs to be an integer keyed object instead of an array to mock a file set
    const files = {
       0: {name: 'test.jpeg'},
       1: {name: 'test.mp4'}
    };
    
    const fileInput = TestUtils.findRenderedDOMComponentWithTag(<testView>, 'input');    
    fileInput.files = files;
    TestUtils.Simulate.change(fileInput)