我收到错误消息Target container is not a DOM element
。使用webpack。
完整错误:
FAIL src/App.test.js
● Test suite failed to run
Invariant Violation: Target container is not a DOM element.
at invariant (node_modules/fbjs/lib/invariant.js:42:15)
at legacyRenderSubtreeIntoContainer (node_modules/react-dom/cjs/react-dom.development.js:17238:34)
at Object.render (node_modules/react-dom/cjs/react-dom.development.js:17317:12)
at Object.<anonymous> (src/index.js:32:20)
at Object.<anonymous> (src/App.test.js:5:14)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:169:7)
App.js
import React, { Component } from 'react';
import './App.scss';
import Tables from './containers/Tables/Tables'
class App extends Component {
render() {
return (
<Tables />
);
}
}
导出默认应用;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { combineReducers, createStore, applyMiddleware, compose } from 'redux';
import thunk from 'redux-thunk';
import aaaApi from '@aaa/aaajs';
import './index.css';
import App from './App';
import tableBuilderReducer from './store/reducers/tableBuilder'
import registerServiceWorker from './registerServiceWorker';
const aaa = new aaaApi('xxx');
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const reducers = {
platforms: tableBuilderReducer('platforms'),
regions: tableBuilderReducer('regions'),
playback: tableBuilderReducer('playback')}
export const store = createStore(
combineReducers(reducers),
composeEnhancers(
applyMiddleware(thunk.withExtraArgument(aaa)),
),
);
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
registerServiceWorker();
App.test.js
import React from 'react'
import Enzyme, { mount, shallow } from 'enzyme'
import Adapter from 'enzyme-adapter-react-16'
import App from './App'
import { store } from './index.js'
Enzyme.configure({ adapter: new Adapter() })
function setup() {
const props = {
sortColumnHandler: jest.fn()
}
const enzymeWraper = mount(<App />)
return {
props,
enzymeWraper
}
}
describe('components', ()=> {
describe('Tables', () => {
it('should render self and sub-components', () => {
const { enzymeWraper } = setup()
})
})
})
答案 0 :(得分:0)
该问题是由测试中包含index.js
引起的,当在ReactDOM.render()
环境创建的文档中未找到root
时,该问题在jsdom
失败。开玩笑。
import { store } from './index.js'
在App.test.js
中是不需要的,因此删除该错误将解决初始错误。
使用mount
中的enzyme
会进行full DOM rendering,并要求为完整渲染设置所有内容。它仅应用于对使用生命周期方法的组件进行单元测试,与DOM交互等。它将完全呈现被测试的组件以及所有子组件。在这种情况下,App
的子代使用redux存储,因此需要在包装Provider
中提供存储,以便使用mount
进行完整渲染。
在大多数情况下,应使用shallow
对React组件进行单元测试。它执行shallow rendering of just the component being tested。在这种情况下,App
是包含Tables
的简单无状态组件,因此使用shallow
是正确的方法。
奖金提示:
将enzyme-to-json安装为dev依赖项,将其作为快照序列化器添加到Jest,然后App.test.js
简化为:
import { shallow } from 'enzyme';
import * as React from 'react';
describe("App", () => {
it('renders as expected', () => {
const component = shallow(<App />);
expect(component).toMatchSnapshot();
});
});