Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix: React onChange/onInput events not triggering on input type="file" file upload #381

Merged
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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}