Skip to content

Provide humane error messages for missing fireEvent() params #355

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

Merged
merged 1 commit into from
Sep 20, 2019
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 18 additions & 0 deletions src/__tests__/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -223,6 +223,24 @@ test('fires shortcut events on Window', () => {
window.removeEventListener('message', clickSpy)
})

test('throws a useful error message when firing events on non-existent nodes', () => {
expect(() => fireEvent(undefined, new MouseEvent('click'))).toThrow(
'Unable to fire a "click" event - please provide a DOM element.',
)
})

test('throws a useful error message when firing events on non-existent nodes (shortcut)', () => {
expect(() => fireEvent.click(undefined)).toThrow(
'Unable to fire a "click" event - please provide a DOM element.',
)
})

test('throws a useful error message when firing non-events', () => {
expect(() => fireEvent(document.createElement('div'), undefined)).toThrow(
'Unable to fire an event - please provide an event object.',
)
})

test('fires events on Document', () => {
const keyDownSpy = jest.fn()
document.addEventListener('keydown', keyDownSpy)
Expand Down
13 changes: 13 additions & 0 deletions src/events.js
Original file line number Diff line number Diff line change
Expand Up @@ -345,6 +345,14 @@ const eventAliasMap = {
}

function fireEvent(element, event) {
if (!event) {
throw new Error(`Unable to fire an event - please provide an event object.`)
}
if (!element) {
throw new Error(
`Unable to fire a "${event.type}" event - please provide a DOM element.`,
)
}
return element.dispatchEvent(event)
}

Expand All @@ -355,6 +363,11 @@ Object.keys(eventMap).forEach(key => {
const eventName = key.toLowerCase()

createEvent[key] = (node, init) => {
if (!node) {
throw new Error(
`Unable to fire a "${key}" event - please provide a DOM element.`,
)
}
const eventInit = {...defaultInit, ...init}
const {target: {value, files, ...targetProperties} = {}} = eventInit
if (value !== undefined) {
Expand Down