2017-06-21 70 views
0

我想爲我的反應應用程序編寫單元測試。我寫的第一個單元測試是遵循反應測試錯誤。目標容器不是DOM元素

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此運行錯誤只有當我用單元測試測試我的程序時才存在。我想知道如何解決這個問題?

這裏是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

除非您已明確載入你的HTML文件到文件,玩笑就無法找到根元素。而在單元測試中,最好不要包含任何超出你需要的東西。

您可以創建的DocumentFragment和渲染元素到它這樣的測試:

it('renders without crashing',() => { 
    const div = document.createElement('div'); // create the div here 
    ReactDOM.render(<Index />, div); 
}); 
+0

不,我試過之前,同樣的錯誤 – Darren

+0

你可以嘗試文件附加到身體像這樣: '文件.body.appendChild(DIV)'。這將在'ReactDOM.render()' –

+0

之前感謝您的幫助。我已經解決了這個錯誤 – Darren

相關問題