Target container is not a DOM element. while testing ReactDOM.render with jest

Viewed 2830

I am testing my index.js file of a basic react project with redux. The file contains ReactDOM.render and i get the above error.

index.js

import React from "react";
import ReactDOM from "react-dom";
import store from "./configureStore";
import { Provider } from "react-redux";
import Favicon from "react-favicon";
import App from "components/App";

function renderToDom() {
  ReactDOM.render(
    <Provider store={store}>
      <App />
    </Provider>,
    document.getElementById("root")
  );
}

renderToDom();
export { renderToDom };

index.test.js

import ReactDOM from "react-dom";
import { mock } from "jest";
import { renderToDom } from "./index";

describe("test ReactDOM.render", () => {
  const originalRender = ReactDOM.render;
  const originalGetElement = global.document.getElementById;
  beforeEach(() => {
    global.document.getElementById = () => true;
    ReactDOM.render = jest.fn();
  });
  afterAll(() => {
    global.document.getElementById = originalGetElement;
    ReactDOM.render = originalRender;
  });
  it("should call ReactDOM.render", () => {
    renderToDom();
    expect(ReactDOM.render).toHaveBeenCalled();
  });
});

I am unable to figure out how to test this index.js file.

1 Answers

The reason this happens is the document generated by jest is empty, it does not contain your root div, so you should add this to your testing code:

const root = document.createElement('div');

    beforeEach(() => {
        document.body.appendChild(root);

        const content = (
            <Provider store={store}>
                <App/>
            </Provider>
        );

        render(
            content,
            root
        );
    });
Related