Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"ReferenceError: document is not defined" when trying to test a create-react-app project

This is my __tests__/App.js file:

import React from 'react';
import ReactDOM from 'react-dom';
import App from '../src/containers/App';

it('renders without crashing', () => {
  const div = document.createElement('div');
  ReactDOM.render(<App />, div);
});

// sanity check
it('one is one', () => {
  expect(1).toEqual(1)
});

And this is the output I get when running yarn test:

FAIL  __tests__/App.js
  ● renders without crashing

    ReferenceError: document is not defined

      at Object.<anonymous>.it (__tests__/App.js:6:15)

  ✕ renders without crashing (1ms)
  ✓ one is one

Test Suites: 1 failed, 1 total
Tests:       1 failed, 1 passed, 2 total
Snapshots:   0 total
Time:        0.128s, estimated 1s
Ran all test suites related to changed files.

Do I need to import another module in order for document to be available here?

Thanks for the help!

like image 320
SeanPlusPlus Avatar asked May 10 '17 19:05

SeanPlusPlus


People also ask

How do I fix document not defined error?

To solve the"ReferenceError: document is not defined" error, make sure to only use the document global variable on the browser. The variable relates to the Document Object Model, which represents a web page that is loaded in the browser and can't be used on the server side (e.g. in Node. js).

Why does it say document is not defined Javascript?

The most common reason for this error is because you're using Node. That is to say, you are trying to access the document object on the server, but the server does not have access to the document object because it lives on the browser.

How do you use document getElementById in react?

The equivalent of the document. getElementById() method in React is using refs. To select an element, set the ref prop on it to the return value of calling the useRef() hook and access the dom element using the current property on the ref , e.g. ref. current .

How do I get Element ID in react?

To get an element by ID in React: Set the ref prop on the element. Use the current property to access the element in the useEffect hook.


3 Answers

For me either of these worked

In package.json file adding test script env flag

"scripts": {
   "test": "react-scripts test --env=jsdom"
}

Using enzyme

 import { shallow } from 'enzyme';

 it('renders without crashing', () => {
  shallow(<App />);
 });
like image 149
HalfWebDev Avatar answered Oct 16 '22 19:10

HalfWebDev


Placing the comment at the top of your unit-test source

/**
 * @jest-environment jsdom
 */

signals jest to mock document and window.

like image 45
jlb Avatar answered Oct 16 '22 18:10

jlb


I set the value in jest.config.js to below and it worked:

testEnvironment: 'jsdom'
like image 31
h-rai Avatar answered Oct 16 '22 17:10

h-rai