I've mocked together a little example - Click Button 1, and 2 more buttons display.
I can test this journey through clicks perfectly fine - However, when I try to test Enter key presses on my button, nothing seems to happen, even though things are logging in the console as expected with the event listeners I've placed in the test.
I've created a sandbox with the code here: https://codesandbox.io/s/gifted-beaver-uetbm?file=/src/tests/app.js
it('should display additional buttons when "Button 1" has been pressed via keyboard', () => {
const {button1, button2} = renderApp()
button1.addEventListener('keydown', () =>
console.log('Button 1 has been pressed - keydown'),
)
fireEvent.keyDown(button1, {
key: 'Enter',
code: 13,
charCode: 13,
keyCode: 13,
})
expect(button2).toBeVisible()
});
I can force this to work in my component by adding an onKeyPress
prop, but that feels like duplicating code for the sake of making a test pass - And I don't like the idea of that when it works as standard in the browser anyway?
<button
onClick={() => setShowButtons(!showButtons)}
// this works, but I don't think I should be duplicating code to appease tests?
// onKeyDown={e => e.keyCode === 13 && setShowButtons(!showButtons)}
>
Button 1
</button>
It seems the fired events are explicitly looking for the events they're tied to, and not byproducts - Such as pressing enter on a button and expecting a click event to fire. Regardless of this being standard browser behaviour? Maybe I'm wrong?
I am well and truly stumped - I feel like this SHOULD work? Any help would be great! Thank you
You need wrap your expect
in a waitFor(() => expect(button2).toBeVisible())