admin管理员组文章数量:1332881
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();
});
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();
});
Share
Improve this question
edited Nov 18, 2024 at 16:40
Drew Reese
204k18 gold badges240 silver badges271 bronze badges
asked Apr 4, 2022 at 5:28
KARTHIKEYAN.AKARTHIKEYAN.A
20.2k10 gold badges137 silver badges149 bronze badges
1
- 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./blog/… – Sambuxc Commented Apr 6, 2022 at 14:59
1 Answer
Reset to default 4Your 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();
});
本文标签: javascriptcreateRoot() Target container is not a DOM element in React Test fileStack Overflow
版权声明:本文标题:javascript - createRoot(...): Target container is not a DOM element in React Test file - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1742311637a2450986.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论