我在我的项目和测试文件中使用 React-18.0.0,我收到以下错误
createRoot(...): Target container is not a DOM element.
我的测试文件是:
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();
});
最佳答案
你的 test
使用 root.render(<App />)
而 React 的 testing-library
提供自己的render
在 test
中使用的函数
检索 root
不需要,并且会导致您显示的错误。
因此,应用以下更改:
// Remove
root.render(<App />);
// Replace with
render(<App />); // Imported from @testing-library/react
工作示例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();
});
关于javascript - 创建根(...): Target container is not a DOM element in React Test file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71732421/