35

I found this implementation here but its using enzyme.

Unit testing React click outside component

Adding an event to window does not work either:

window.addEventListener('click', () => {
      console.log('click on window');
    });

Has anyone came across this issue above using jest and "@testing-library/react"?

2
  • 5
    Did you try to run fireEvent.click(document)? Commented Jul 11, 2019 at 14:08
  • That worked. Thanks @GiorgioPolvara-Gpx Commented Jul 11, 2019 at 15:26

2 Answers 2

42

as @Giorgio mentioned:

fireEvent.click(document)

//or

userEvent.click(document.body);
Sign up to request clarification or add additional context in comments.

Comments

23

I'd like to provide an up-to-date answer which follows the same principle as what @eduardomoroni proposed. The fireEvent hasn't worked for me and so I've managed to achieve it with the userEvent api.

userEvent.click(document.body);

Also, as typescript complains document cannot be passed to the click event handler. Instead, the body is a better solution.

Argument of type 'Document' is not assignable to parameter of type 'TargetElement'.

6 Comments

Please explain where does the mysterious userEvent comes from
fireEvent.click(document.body) worked for me
This works! Thank you so much :)
for me, I had to do fireEvent.mouseDown(document);
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.