gpt4 book ai didi

javascript - 确保为 enzyme 加载 dom 环境

转载 作者:行者123 更新时间:2023-12-01 23:04:17 24 4
gpt4 key购买 nike

当我从命令行在 Jest 中测试 React 应用程序时,使用 Enzyme 的 mount 函数时遇到以下错误。它说 DOM 环境未加载,我认为这意味着我需要设置 JSDOM。然而,似乎JSDOM ships with Jest and is preconfigured根据 Facebook 的 Jest 文档。这是我的测试:

import React from 'react'
import MyComponent from '../src/components/MyComponent'
import { configure } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import { mount, shallow } from 'enzyme'
import { Menu, Dropdown, Modal } from 'semantic-ui-react'
import renderer from 'react-test-renderer';

configure({ adapter: new Adapter() })

test('it works', () => {
const wrapper = mount(
<MyComponent />
)
expect(wrapper.contains('foobar')).toEqual(true)
});

这是错误:

Enzyme's mount expects a DOM environment to be loaded, but found none

at assertDomAvailable (node_modules/enzyme-adapter-utils/build/Utils.js:107:11)
at ReactSixteenAdapter.createMountRenderer (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:203:52)
at ReactSixteenAdapter.createRenderer (node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:384:25)
at new ReactWrapper (node_modules/enzyme/build/ReactWrapper.js:96:54)
at mount (node_modules/enzyme/build/mount.js:19:10)
at Object.<anonymous> (test/LinesheetModal.test.js:12:37)
at new Promise (<anonymous>)

它似乎与enzyme-adapter-react-16有关。知道可能出了什么问题吗?

最佳答案

看起来问题是 JSDOM 和 Enzyme 设置不正确。将此文件作为预加载文件添加到 Jest 中修复了该问题:

import Adapter from 'enzyme-adapter-react-16'
import { configure } from 'enzyme'
import jsdom from 'jsdom'

function setUpDomEnvironment() {
const { JSDOM } = jsdom;
const dom = new JSDOM('<!doctype html><html><body></body></html>', {url: 'http://localhost/'});
const { window } = dom;

global.window = window;
global.document = window.document;
global.navigator = {
userAgent: 'node.js',
};
copyProps(window, global);
}

function copyProps(src, target) {
const props = Object.getOwnPropertyNames(src)
.filter(prop => typeof target[prop] === 'undefined')
.map(prop => Object.getOwnPropertyDescriptor(src, prop));
Object.defineProperties(target, props);
}

setUpDomEnvironment();

configure({ adapter: new Adapter() })

关于javascript - 确保为 enzyme 加载 dom 环境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46896639/

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