createRoot(...):目标容器不是 DOM 元素。 (使用 Jest 和 React 测试库时)

问题描述 投票:0回答:1

请帮助我解决此错误,我正在尝试为我的应用程序组件创建一个测试,以确保 initialeTimes() 函数按预期工作并返回下面提到的对象。

但是,当我运行测试时,它给出了以下错误:

createRoot(...): Target container is not a DOM element .import {BrowserRouter} from "react-router-dom" 
   6 |
>  7 | const root = ReactDOM.createRoot(document.getElementById('root'));
     |                       ^
   8 | root.render(
   9 |   <React.StrictMode>
  10 |     <BrowserRouter>.

这是 App.js 的代码:

import {React, useReducer} from 'react';
import {Routes, Route} from "react-router-dom"
import './App.css';
import BookingPage from './components/BookingPage';
import Home from './components/Home';

function updateTimes(availableTimes, action)
{
  switch(action.type)
  {
    case 'SET_DATE':
        return {...availableTimes, select: action.payload};
    default:
      return availableTimes;
  }
}

export function  initializeTimes()
{
  return {select : null};
}


const App = ()  =>{
  const [availableTimes, dispatch] = useReducer(updateTimes, initializeTimes);

  return (
    <Routes>
        <Route path="/" element={<Home />} />
        <Route path="/booking" element={<BookingPage availableTimes={availableTimes} dispatch={dispatch} />} />
    </Routes>
  ) 
}

export default App;

这就是测试:

// App.test.js
import '@testing-library/jest-dom';
import { initializeTimes } from '../App'; 

test('initializeTimes returns the expected object', () => {
    const res = initializeTimes()
    expect(res).toEqual({ select: null });
});

我也尝试过:

// App.test.js
import '@testing-library/jest-dom';
import App, { initializeTimes } from '../App';

test('initializeTimes returns the expected object', () => {
    render(<App/>)
    const res = initializeTimes()
    expect(res).toEqual({ select: null });
});

我手动更新并安装了 jest,但问题仍然发生。我将不胜感激任何帮助!

reactjs jestjs react-testing-library react-dom
1个回答
0
投票

第一个测试代码块很好,它应该可以工作。

您的项目环境中还有其他测试文件吗?那些在 React 组件上调用“render”的?第一个代码块甚至没有进行任何调用来渲染 React 组件,因此如果这是您拥有的唯一测试文件,则在这方面不应抛出任何错误。

如果这是唯一的测试文件,你确定你已经正确初始化了React吗? - 您没有显示创建根目录的文件。

© www.soinside.com 2019 - 2024. All rights reserved.