"ReferenceError: document not defined" when trying to test create-response-app project

This is my file __tests__/App.js:

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 result that I get at startup 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 to documentbe available here?

Thanks for the help!

+16
source share
3 answers

For me, any of them worked

In the package add file file.json script the env flag

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

Enzyme use

 import { shallow } from 'enzyme';

 it('renders without crashing', () => {
  shallow(<App />);
 });
+26
source

Posting a comment at the top of the source for a unit test

/**
 * @jest-environment jsdom
 */

signals a joke on the document and the window.

+1
source

create-react-app, yarn test yarn jest - .

0
source

Source: https://habr.com/ru/post/1676868/


All Articles