Search code examples
reactjsjestjsmaterial-uireact-testing-library

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


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?


Solution

  • 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.