Last active
May 3, 2017 17:17
-
-
Save billjohnston/5b98ae758f4b37c95a4397cae6d98e68 to your computer and use it in GitHub Desktop.
Mock a file input onChange event for testing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
export default const mockFileUpload = (fileInput, fileUrl) => new Promise((resolve, reject) => { | |
try { | |
const xhr = new XMLHttpRequest() | |
xhr.open('GET', fileUrl, true) | |
xhr.responseType = 'blob' | |
xhr.onload = (e) => { | |
if (xhr.status == 200) { | |
fileInput.files[0] = xhr.response | |
const mockEvent = document.createEvent('HTMLEvents') | |
mockEvent.initEvent('change', true, true) | |
fileInput.dispatchEvent(mockEvent) | |
resolve() | |
} else { | |
throw new Error('Error fetching file') | |
} | |
} | |
xhr.send() | |
} catch (error) { | |
reject(error) | |
} | |
}) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment