0

Hi I have components as shown below:

<ParentComponent>
   <ChildComponent />
</ParentComponent>

ChildComponent.js----
someFunction = () => {
  const val = document.querySelector('#someId').addEventListener('mouseup', mouseHandler);
  // some calculation on val
};

Inside my Parent.test.js, my test fails, saying:

Cannot read property 'addEventListener' of null

Let me know, how to make my test pass and where am I going wrong.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
Uzair Khan
  • 2,812
  • 7
  • 30
  • 48
  • 1
    What's the context - why are you using querySelector alongside React? – jonrsharpe Oct 18 '20 at 16:14
  • 1
    Jest recommends using `jsdom` when to simulate DOM functionalities. Can you add `jsdom` to your package.json and configure your Jest config file to use it? One of the examples can be found here : https://jestjs.io/docs/en/tutorial-jquery – Kanishk Anand Oct 18 '20 at 16:20
  • @jonrsharpe - its a very peculiar requirement, I've simplified to display the question here. – Uzair Khan Oct 18 '20 at 16:24
  • 1
    @KanishkAnand `jsdom` is the *default* Jest test environment: https://jestjs.io/docs/en/configuration#testenvironment-string – jonrsharpe Oct 18 '20 at 16:25
  • @Kanishk Anand - problem is how do I mock document.querySelector so that it does not throw null, and because it is null, it throws Cannot read property 'addEventListener' of null – Uzair Khan Oct 18 '20 at 16:25
  • 1
    Can you try this? https://stackoverflow.com/questions/41098009/mocking-document-in-jest As per my understanding, with JSDOM you need not mock individual functions, it handles that for you. – Kanishk Anand Oct 18 '20 at 16:29
  • 1
    If you happen to setup your project with `create-react-app`, you got `@testing-library/react` at your disposal, so you may use `render` method to return `wrapper` object, mocking your DOM, then use `wrapper.querySelector(#someId)` – Yevhen Horbunkov Oct 18 '20 at 17:03

0 Answers0