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

前端 未结 4 2290
醉话见心
醉话见心 2021-02-18 13:42

This is my __tests__/App.js file:

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

it(\'         


        
相关标签:
4条回答
  • 2021-02-18 14:22

    In the package.json if using jest

    "scripts":{
          "test": "jest --env=jsdom"
    }
    
    0 讨论(0)
  • 2021-02-18 14:28

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

    /**
     * @jest-environment jsdom
     */
    

    signals jest to mock document and window.

    0 讨论(0)
  • 2021-02-18 14:32

    If you are using create-react-app, make sure to run yarn test instead of yarn jest or something else.

    0 讨论(0)
  • 2021-02-18 14:35

    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 />);
     });
    
    0 讨论(0)
提交回复
热议问题