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

a1o7rhls  于 5个月前  发布在  Jest
关注(0)|答案(1)|浏览(67)

请我需要帮助,以获得这个错误的骑,我试图创建一个测试我的应用程序组件,我确保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,但问题继续发生。我会感谢任何帮助!

py49o6xq

py49o6xq1#

第一个测试代码块是好的,它应该工作。
你的项目环境中还有其他测试文件吗?那些在React组件上调用'render'的测试文件?第一个代码块甚至没有调用任何渲染React组件的代码,所以如果这是你唯一的测试文件,那么在这方面应该不会抛出错误。
如果这是唯一的测试文件,你确定你已经正确地初始化了React吗?-你没有显示你的文件,其中创建了根。

相关问题