gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:23:07 24 4
gpt4 key购买 nike

这是我的 __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 在这里可用?

感谢您的帮助!

最佳答案

对我来说,这些都有效

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

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

使用 enzyme

 import { shallow } from 'enzyme';

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

关于javascript - 尝试测试 create-react-app 项目时出现 "ReferenceError: document is not defined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43901660/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com