25

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"?

skyboyer
  • 22,209
  • 7
  • 57
  • 64
user992731
  • 3,400
  • 9
  • 53
  • 83

2 Answers2

29

as @Giorgio mentioned:

fireEvent.click(document)

//or

userEvent.click(document.body);
eduardomoroni
  • 4,140
  • 1
  • 21
  • 18
20

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

Nemanja Milosavljevic
  • 1,251
  • 18
  • 33