Kar*_*ora 63 unit-testing reactjs jestjs react-dom react-testing-library
更新到 React 18 或从 创建新的 React 18 应用程序后create-react-app,当我运行该yarn test命令时,它会为任何测试中使用的console.error每个方法发出警告,如下所示:render
console.error
警告:ReactDOM.render 在 React 18 中不再支持。请改用 createRoot。在您切换到新 API 之前,您的应用程序的行为就像运行 React 17 一样。了解更多信息:https ://reactjs.org/link/switch-to-createroot
由于 React 测试库目前似乎不支持 React 18 方法。
Fer*_*han 79
解决react测试库错误:
"ReactDOM.render is no longer supported in React 18, update the version of the react testing library."
在项目根目录中打开终端并运行以下命令:
npm install --save-dev @testing-library/react@latest
npm install --save-dev @testing-library/jest-dom@latest
npm install --save-dev @testing-library/user-event@latest
Run Code Online (Sandbox Code Playgroud)
确保更新您正在使用的所有反应测试库包的版本。
您的index.js 文件应使用新的createRoot API 来呈现您的应用程序。
索引.js
import React from 'react';
import ReactDOM from "react-dom/client";
import App from './App';
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(
<React.StrictMode>
<App />
</React.StrictMode>
);
Run Code Online (Sandbox Code Playgroud)
现在您应该能够开始测试而不会出现错误。
应用程序.test.js
import {render, screen} from '@testing-library/react';
import App from './App';
test('renders react component', () => {
render(<App />);
const divElement = screen.getByText(/hello world/i);
expect(divElement).toBeInTheDocument();
});
Run Code Online (Sandbox Code Playgroud)
Joe*_*ugh 11
卸载@testing-library/react-hook并导入renderHook自@testing-library/react
import { renderHook } from "@testing-library/react";
Run Code Online (Sandbox Code Playgroud)
请参阅此处https://github.com/testing-library/react-hooks-testing-library/issues/826#issuecomment-1100650242
| 归档时间: |
|
| 查看次数: |
48898 次 |
| 最近记录: |