尝试测试create-react-app项目时,"ReferenceError:document not defined"

Sea*_*lus 16 javascript reactjs jestjs create-react-app

这是我的__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)
});
Run Code Online (Sandbox Code Playgroud)

这是我在运行时得到的输出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.
Run Code Online (Sandbox Code Playgroud)

我是否需要导入另一个模块才能document在此处使用?

谢谢您的帮助!

kus*_*lvm 27

对我来说,这些都有效

在package.json文件中添加测试脚本env标志

"scripts": {
   "test": "react-scripts test --env=jsdom"
}
Run Code Online (Sandbox Code Playgroud)

用酶

 import { shallow } from 'enzyme';

 it('renders without crashing', () => {
  shallow(<App />);
 });
Run Code Online (Sandbox Code Playgroud)


h-r*_*rai 12

我将值设置jest.config.js为下面并且它起作用了:

testEnvironment: 'jsdom'
Run Code Online (Sandbox Code Playgroud)

  • 我想这是最好的答案! (2认同)
  • 这很有效,只需确保您有“jest-environment-jsdom”即可。 (2认同)

小智 9

如果使用 jest 在 package.json 中

"scripts":{
      "test": "jest --env=jsdom"
}
Run Code Online (Sandbox Code Playgroud)


jlb*_*jlb 6

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

/**
 * @jest-environment jsdom
 */
Run Code Online (Sandbox Code Playgroud)

signals jest to mock document and window.