Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 393
Herman Avatar asked Jan 03 '20 01:01

Herman


People also ask

What is the difference between userEvent and fireEvent?

fireEvent dispatches exactly the events you tell it to and just those - even if those exact events never had been dispatched in a real interaction in a browser. User-event on the other hand dispatches the events like they would happen if a user interacted with the document.

Does fireEvent need act?

You NEVER need to wrap userEvent or fireEvent in act. They are *already* wrapped in act. Some have noticed that they see an "act warning" go away when wrapping these in an async act. The warning would go away just as well if you added: `await act(async () => {})` on the next line.


1 Answers

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.

like image 109
Herman Avatar answered Oct 17 '22 07:10

Herman