createRoot(...): Target container is not a DOM element in React Test file
Asked Answered
G

1

6

I'm using React-18.0.0 in my project and in the test file I'm getting an error something below

createRoot(...): Target container is not a DOM element.

My test file is :

import ReactDOM from 'react-dom/client';
import { render, screen } from "@testing-library/react";
import App from "./App";

const root = ReactDOM.createRoot(document.getElementById("root"));

test("renders learn react link", () => {
    root.render(<App />);
    const linkElement = screen.getByText(/Hello React/i);
    expect(linkElement).toBeInTheDocument();
});
Gastineau answered 4/4, 2022 at 5:28 Comment(1)
This article helped me. I was using the ID in my App.js but its the root ID in the index.html file - bobbyhadz.com/blog/…Feticide
L
4

Your test uses root.render(<App />) while React's testing-library provides there own render function to use inside a test

Retrieving the root isn't needed, and is causing the error you're showing.

So, apply the following change:

// Remove
root.render(<App />);

// Replace with
render(<App />);  // Imported from @testing-library/react

Example of working App.test.js:

import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
    render(<App />);
    const linkElement = screen.getByText(/this should exist/i);
    expect(linkElement).toBeInTheDocument();
});
Logic answered 13/4, 2022 at 12:3 Comment(1)
I am also using import {render} from "@testing-library/react"; with vitest but still getting the same error Error: createRoot(...): Target container is not a DOM element. ❯ createRoot node_modules/react-dom/cjs/react-dom.development.js:29345:11Parton

© 2022 - 2024 — McMap. All rights reserved.