fireEvent.keyDown not working as expected on my Jest + React Testing Library test
Asked Answered
E

2

22

In my current React project, I'm testing a component which includes, as child component, the Dialog component from Material UI.

It's supposed it has to run the onClose() function when the user presses the Esc key. I tested it manually and it works perfectly well. Now I'm doing the same test, this time using Jest + React Testing Library. You can see the code below:

fireEvent.keyDown(container, {
      key: "Escape",
      code: "Escape",
      keyCode: 27,
      charCode: 27
    });

And the test doesn't pass. After some debugs, I've realized that the event is actually being triggered, but for some reason is not having an impact on the <Dialog/> component.

So I did run the component on Google Chrome, and triggered the same event from the Dev Tools console with the following code:

document.dispatchEvent(
    new KeyboardEvent(
        "keydown", {     
            key: "Escape",
            code: "Escape",
            keyCode: 27,
            charCode: 27
        }
    )
);

...and it doesn't work either.

What can I do to make this test pass?

Ellison answered 3/1, 2020 at 1:59 Comment(5)
What is container? In the test you are firing the event on the container, but this may not be the case when using the app in the browser.Latoshalatouche
The container is the wrapper component. But in the case of Material UI Dialog, the Escape key should work, no matter where is the focusEllison
Can you provide a Code Sandbox ?Discography
@Latoshalatouche you were right. The problem was the target of the eventEllison
Glad you managed to fix it!Latoshalatouche
E
39

The user JMadelaine was right, and I've found what was wrong. The event target shouldn't be the container nor document, but the dialog box itself. So now I've changed the code from this:

fireEvent.keyDown(container, {
      key: "Escape",
      code: "Escape",
      keyCode: 27,
      charCode: 27
});

...to this:

fireEvent.keyDown(getByText(/the text in the dialog box/i), {
      key: "Escape",
      code: "Escape",
      keyCode: 27,
      charCode: 27
});

And it works.

Ellison answered 4/1, 2020 at 12:59 Comment(4)
Not working for me, but also you may want to add await to the fireEventResendez
@Resendez this failed for me as well initially. Changing keyCode and charCode to number instead of a string worked for me....Zwolle
Related: simple utility to see keycode info: justingolden.me/keycode (some are only supported in older browsers and some in newer browsers. Check caniuse)Resendez
Legend this solved my issue! Thanks :)Fearful
I
1
  it('calls setShowModal on escape key', () => {
    render(<ModalPopUp {...props}>children</ModalPopUp>)
    const event = new KeyboardEvent('keydown', { key: 'Escape' })
    document.dispatchEvent(event)
    expect(props.setShowModal).toBeCalled()
  })
Interrogate answered 7/12, 2022 at 14:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.