我想为我的反应应用程序编写单元测试。我写的第一个单元测试如下
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
运行它只有当我用单元测试测试程序时才会出现此错误。我想知道如何解决这个问题?
以下是root 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();
});
答案 0 :(得分:0)
除非您已将html文件明确加载到文档中,否则jest将无法找到该根元素。在单元测试中,最好不要包含任何超出需要的内容。
你可以创建一个documentFragment并将元素渲染到它上面进行测试,如下所示:
it('renders without crashing', () => {
const div = document.createElement('div'); // create the div here
ReactDOM.render(<Index />, div);
});