【发布时间】:2017-11-24 22:22:26
【问题描述】:
我想为我的 react 应用程序编写单元测试。我写的第一个单元测试如下
it('renders without crashing', () => {
const div = document.getElementById('root');
ReactDOM.render(<Index />, div);
});
但是我得到了错误
Invariant Violation: _registerComponent(...): Target container is not a DOM element.
不得不说,我写的应用程序其实是没有这个错误的,如果我用npm start运行的话,这个错误只有在我用单元测试测试我的程序时才会出现。我想知道如何解决这个问题?
这是用于根 div 渲染的 index.js 文件
import React from 'react';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import '../style/style.css';
import configurationStore from './store/configurationStore';
const store = configurationStore();
// TODO: Comments;
render (
<Provider store={store}>
<Router history={browserHistory} routes={routes}/>
</Provider>,
document.getElementById('root')
);
这是我的html文件
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIzaSyDLjwDjIMWnBb8C6Nrc-38HcWfVK5nmVhM&libraries=places"></script>
<link href="https://fonts.googleapis.com/css?family=Roboto:300,400,500" rel="stylesheet">
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css">
<!-- Optional theme -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap-theme.min.css">
<script src="https://cdn.auth0.com/js/lock/10.6/lock.min.js"></script>
<script src="https://apis.google.com/js/platform.js" async defer></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<title>React App</title>
</head>
<body>
<img alt="background image" src="http://www.viudigital.com/images/viu_bg_temp.jpg?crc=524745911" id="fullscreen" />
<div id="root"></div>
</body>
</html>
解决方案: 我找到了解决此错误的解决方案。要修复它,只需将我们要测试的组件包装到根组件中即可。这是一个测试示例
test('Header component rendered properly', () => {
const tree = renderer.create(
<App>
<Header />
</App>
).toJSON();
expect(tree).toMatchSnapshot();
});
【问题讨论】:
标签: javascript node.js unit-testing reactjs testing