Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Test suite failed to run. Invariant Violation: _registerComponent(...): Target container is not a DOM element

I am trying to test my react component's render, but getting the error below: Invariant Violation: _registerComponent(...): Target container is not a DOM element. Error doesn't exist if i change the place where follows render my component on document.body , and it exists if this place is some div with some id in body.

Here my component:

import React, {Component} from 'react';
{render} from 'react-dom';
import Demo from './demo/demo'
import Demo2 from  './demo2/demo2'
require('./app-styles.sass')

export class App extends Component {
render() {
    return (
           <div>
               <Demo2 />
               <Demo />
               <div>Hello jest from react</div>
           </div>
       );
   }
}
render(<App/>, document.getElementById('helloWorldRoot'));

Test of this component:

import React from 'react'
import {shallow, mount} from 'enzyme'
import {App} from './app'

describe('base component', () => {
  it('renders as a div', () => {
    const application = shallow(<App />);
    expect(application).toMatchSnapshot();
  });
});

And here is my html:

    <!DOCTYPE html>
    <html>
    <head>
      <title>Hello jests' tests</title>
      <link rel="stylesheet" href="dist/app.css">
    </head>

    <body>
      <div id="helloWorldRoot"></div>
      <script type="text/javascript" src="dist/app.js"></script>
    </body>

What is the problem here? I will be glad to some advice.

like image 242
Artem Z. Avatar asked Apr 24 '17 14:04

Artem Z.


1 Answers

The file you're testing, app.js, is attempting to find a DOM element with ID helloWorldRoot in the last line. This DOM element does not exist when the element is being rendered by Enzyme - hence the error message.

To fix this, separate the <App /> component and rendering of it into two files. Make sure the file that mounts the application to the DOM (let's call it main.js) does just this one thing and nothing else. The other file, app.js, can then be tested using Jest and Enzyme.

So main.js should do no more than:

import React from 'react';
import { render } from 'react-dom';
import App from './app';

render(<App/>, document.getElementById('helloWorldRoot'));

And of course the corresponding lines should be removed from app.js.

like image 158
mthmulders Avatar answered Oct 02 '22 16:10

mthmulders