尝试测试 create-react-app 项目时出现“ReferenceError: document is not defined”

IT技术 javascript reactjs jestjs create-react-app
2021-05-08 20:13:49

这是我的__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)
});

这是我运行时得到的输出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.

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

谢谢您的帮助!

4个回答

对我来说,其中任何一个都有效

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

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

使用酶

 import { shallow } from 'enzyme';

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

将注释放在单元测试源的顶部

/**
 * @jest-environment jsdom
 */

用开玩笑的信号来模拟文档和窗口。

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

testEnvironment: 'jsdom'

如果使用 jest 在 package.json 中

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