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"?
Jest is a JavaScript test runner that provides resources for writing and running tests. React Testing Library offers a set of testing helpers that structure your tests based on user interactions rather than components' implementation details.
In these docs we'll demonstrate configuring Jest, but you should be able to do similar things with any testing framework (React Testing Library does not require that you use Jest).
Shallow rendering is one way that Enzyme keeps tests simpler than Jest. When you shallow-render a component with Enzyme, you render only that component. Enzyme doesn't render any of the children of that component. This is a useful restriction that ensures that you aren't testing too much in one test.
It's a great library, it's (relatively) easy to start using, and it encourages good testing practices. Note – you can also use it without Jest. "The more your tests resemble the way your software is used, the more confidence they can give you."
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'.
as @Giorgio mentioned:
fireEvent.click(document)
//or
userEvent.click(document.body);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With