“参考错误:文档未定义"尝试测试 create-react-app 项目时 [英] "ReferenceError: document is not defined" when trying to test a create-react-app project
本文介绍了“参考错误:文档未定义"尝试测试 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)
});
这是我在运行 yarn test
时得到的输出:
And this is the output I get when running 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
在此处可用?
Do I need to import another module in order for document
to be available here?
感谢您的帮助!
推荐答案
对我来说,这两种方法都行得通
For me either of these worked
在 package.json 文件中添加测试脚本环境标志
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 />);
});
这篇关于“参考错误:文档未定义"尝试测试 create-react-app 项目时的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文