“ ReferenceError:未定义文档”。尝试测试create-react-app项目时 [英] "ReferenceError: document is not defined" when trying to test a create-react-app project

查看:70
本文介绍了“ ReferenceError:未定义文档”。尝试测试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)
});

这是运行纱线测试

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 for document to be available here?

感谢您的帮助!

推荐答案

对我来说,这两个都有效

For me either of these worked

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

In package.json file adding test script env flag

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

使用酶

 import { shallow } from 'enzyme';

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

这篇关于“ ReferenceError:未定义文档”。尝试测试create-react-app项目时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆