【问题标题】:"ReferenceError: document is not defined" when trying to test a create-react-app project尝试测试 create-react-app 项目时出现“ReferenceError:文档未定义”
【发布时间】:2017-10-09 15:27:54
【问题描述】:

这是我的__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.

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

感谢您的帮助!

【问题讨论】:

标签: javascript reactjs jestjs create-react-app


【解决方案1】:

把它放在你的 index.test.js(或测试文件)之上。不要放在中间或末端。

/** * @jest-environment jsdom */

【讨论】:

    【解决方案2】:

    我刚刚遇到了这个问题,2021 年 9 月。我正在学习 react 中的测试,我通过进入 node_modules 文件夹解决了这个问题。 在那个文件夹里面有一个 jest 文件夹。在 jest 文件夹中有一个 package.json 文件。 在那个 package.json 文件中,我插入了一个东西。类似于上面有人提到的。

    package.json 文件

    "testEnvironment": "jsdom"

    我知道一般我不应该编辑 node_modules 文件夹,但只是为了继续学习,这将不得不这样做。

    我不知道对于更严肃的项目是否需要其他解决方案。

    【讨论】:

    • 最好在package.jsonjest对象下添加这个
    • 是的,威廉,我后来找到了那个解决方案。谢谢
    【解决方案3】:

    我将jest.config.js 中的值设置为以下,它起作用了:

    testEnvironment: 'jsdom'
    

    【讨论】:

    • 谢谢。我喜欢这个答案,因为我不必自己编辑 package.json。
    • 我认为这是最好的答案!
    • 这是最好的答案,因为使用 jest 配置文件来设置这个环境,太棒了。
    • 为我工作。谢谢
    【解决方案4】:

    如果使用 jest,则在 package.json 中

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

    【讨论】:

      【解决方案5】:

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

      /**
       * @jest-environment jsdom
       */
      

      发出嘲笑来模拟文档和窗口。

      【讨论】:

      • 谢谢,这是唯一有效的方法!
      【解决方案6】:

      对我来说,这两种方法都有效

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

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

      使用酶

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

      【讨论】:

        【解决方案7】:

        如果您使用的是create-react-app,请确保运行yarn test 而不是yarn jest 或其他内容。

        【讨论】:

          猜你喜欢
          • 2019-08-23
          • 1970-01-01
          • 1970-01-01
          • 2019-09-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多