Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing React click outside component using Jest and react testing library

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

like image 900
user992731 Avatar asked Jul 10 '19 20:07

user992731


People also ask

What is the difference between React testing library and Jest?

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.

Does React testing library use Jest?

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

Which is better Enzyme or 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.

Can you use React testing library without Jest?

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


2 Answers

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

like image 154
Nemanja Milosavljevic Avatar answered Sep 17 '22 02:09

Nemanja Milosavljevic


as @Giorgio mentioned:

fireEvent.click(document)

//or

userEvent.click(document.body);
like image 36
eduardomoroni Avatar answered Sep 19 '22 02:09

eduardomoroni