User-event: Support "enter" keydown on button

Created on 9 Oct 2019  路  9Comments  路  Source: testing-library/user-event

In a browser, enter keydown trigger the click event of the button.

It would be nice if the user-event library support this behavior.

You can test the browser behavior here: https://codesandbox.io/s/jovial-glitter-jy883?from-embed

A naive implementation would be to add a keyDown function to user-event:

    keyDown(element, options) {
        fireEvent.keyDown(element, options);

        if (element.tagName === "BUTTON") {
            fireEvent.click(element);
        }
    }

Thank you,

Patrick

Most helpful comment

This is now supported with userEvent.type(button, '{enter}')

All 9 comments

Hmm, but here you aren't testing for the enter-key but now everything can trigger the click event?

Does that work on all elements though? Or just form controls?

Good question, I would assume it's a typical button behaviour?

I wrote my own test and got some interesting results: https://codepen.io/nickmccurdy/pen/RwweGxG?editors=1010

To summarize, all buttons (using <button> or <input type="some button type">) except radio buttons fire click events when return is hit. Radio buttons only fire click events when space is hit. As far as I'm aware, others elements do not fire click events on key press.

Okay, thanks for testing this @nickmccurdy!
Thinking now how to best way to implement this 馃

This would be super helpful for me as well, due to this issue w/ fireEvent. https://github.com/testing-library/react-testing-library/issues/551

In my case, I have to support a submit-like event for textarea's onKeyPress for "Enter".

This is now supported with userEvent.type(button, '{enter}')

@kentcdodds Awesome! Thanks so much :)

Regarding '{enter}' it looks like they're still just using fireEvent.keyDown internally:

https://github.com/testing-library/user-event/blob/4bbb4b9a6e33641bb2bec3830b6f97e373e29541/src/type.js#L109-L118

Was this page helpful?
0 / 5 - 0 ratings