Skip to content

Instantly share code, notes, and snippets.

@billjohnston
Last active May 3, 2017 17:17
Show Gist options
  • Save billjohnston/5b98ae758f4b37c95a4397cae6d98e68 to your computer and use it in GitHub Desktop.
Save billjohnston/5b98ae758f4b37c95a4397cae6d98e68 to your computer and use it in GitHub Desktop.
Mock a file input onChange event for testing
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