javascript - 创建根(...): Target container is not a DOM element in React Test file

标签 javascript reactjs react-testing-library react-test-renderer react-18

我在我的项目和测试文件中使用 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 提供自己的rendertest 中使用的函数

检索 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/

相关文章:

javascript - 从 Meteor.method 中的回调返回值

javascript - 如何使用 Velocity.js 制作渐变偏移动画

javascript - 我希望有人帮助我理解几行代码。有人可以帮我解释一下吗?谢谢

reactjs - 使用react-testing-library渲染方法不起作用

javascript - 你如何检查 react 测试库中的复选框?

javascript - 单击 div 上的关闭按钮并触发 div click()

javascript - 什么是虚拟 DOM?

reactjs - React - props 未定义

javascript - 如何从 React 中的另一个静态方法调用静态方法?

reactjs - 使用 React/Typescript 在 test-utils 中扩展 React 测试库的自定义渲染的返回类型是什么?