Skip to content

Commit

Permalink
fix: React onChange/onInput events not triggering on input type="file…
Browse files Browse the repository at this point in the history
…" file upload (#381)

* fix: upload change/input events not bubbling up

* test: upload function change/input event bubbling

* test: updated upload with label test to reflect event bubbling

Co-authored-by: Kent C. Dodds <me+github@kentcdodds.com>

Closes #380
  • Loading branch information
ybentz committed Jun 25, 2020
1 parent 75bab48 commit d4db93c
Show file tree
Hide file tree
Showing 2 changed files with 44 additions and 8 deletions.
38 changes: 37 additions & 1 deletion src/__tests__/upload.js
@@ -1,5 +1,5 @@
import userEvent from '../'
import {setup} from './helpers/utils'
import {setup, addListeners} from './helpers/utils'

test('should fire the correct events for input', () => {
const file = new File(['hello'], 'hello.png', {type: 'image/png'})
Expand Down Expand Up @@ -61,6 +61,8 @@ test('should fire the correct events with label', () => {
label[for="element"] - click: Left (0)
input#element[value=""] - click: Left (0)
input#element[value=""] - focusin
input#element[value=""] - input
input#element[value=""] - change
`)
})

Expand Down Expand Up @@ -125,3 +127,37 @@ test('should not upload when is disabled', () => {
expect(element.files.item(0)).toBeNull()
expect(element.files).toHaveLength(0)
})

test('should call onChange/input bubbling up the event when a file is selected', () => {
const file = new File(['hello'], 'hello.png', {type: 'image/png'})

const {element: form} = setup(`
<form>
<input type="file" />
</form>
`)
const input = form.querySelector('input')

const onChangeInput = jest.fn()
const onChangeForm = jest.fn()
const onInputInput = jest.fn()
const onInputForm = jest.fn()
addListeners(input, {
eventHandlers: {change: onChangeInput, input: onInputInput},
})
addListeners(form, {
eventHandlers: {change: onChangeForm, input: onInputForm},
})

expect(onChangeInput).toHaveBeenCalledTimes(0)
expect(onChangeForm).toHaveBeenCalledTimes(0)
expect(onInputInput).toHaveBeenCalledTimes(0)
expect(onInputForm).toHaveBeenCalledTimes(0)

userEvent.upload(input, file)

expect(onChangeForm).toHaveBeenCalledTimes(1)
expect(onChangeInput).toHaveBeenCalledTimes(1)
expect(onInputInput).toHaveBeenCalledTimes(1)
expect(onInputForm).toHaveBeenCalledTimes(1)
})
14 changes: 7 additions & 7 deletions src/upload.js
Expand Up @@ -35,17 +35,17 @@ function upload(element, fileOrFiles, init) {
input,
createEvent('input', input, {
target: {files: inputFiles},
bubbles: true,
cancelable: false,
composed: true,
...init,
}),
)

fireEvent(
input,
createEvent('change', input, {
target: {files: inputFiles},
...init,
}),
)
fireEvent.change(input, {
target: {files: inputFiles},
...init,
})
}

export {upload}

0 comments on commit d4db93c

Please sign in to comment.