【问题标题】:React test fails becasue target container is not a DOM elementReact 测试失败,因为目标容器不是 DOM 元素
【发布时间】:2020-12-06 15:51:18
【问题描述】:

我正在尝试运行组件测试,但由于目标容器不是 DOM 元素,因此测试器不断失败。我找到了一个建议从 index.tsx 中删除导出值的答案,但它没有解决问题。

src/Component/__tests__/FirstPage.test.tsx
  ● Test suite failed to run

    Target container is not a DOM element.

       8 | export const socket = io('http://localhost:8080');  
       9 | 
    > 10 | ReactDOM.render(
         |          ^
      11 |   <React.StrictMode>
      12 |     <App/>
      13 |   </React.StrictMode>,

      at Object.render (node_modules/react-dom/cjs/react-dom.development.js:26091:13)

这是我的 App.tsx 文件

import React, { Component } from "react";
import './App.css';
import FirstPage from './Component/FirstPage/FirstPage';

export default class App extends Component {

  render() {
    return (
      <FirstPage/>
    );
  }
}


这里是 index.tsx 文件:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import io from 'socket.io-client';
import App from './App';
import reportWebVitals from './reportWebVitals';

export const socket = io('http://localhost:8080');

ReactDOM.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>,
  document.getElementById('root')
);

// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
// or send to an analytics endpoint
reportWebVitals();

这是测试

import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import React from 'react';
import FirstPage from '../FirstPage/FirstPage';
import User from '../User/User';

const testUser = new User("testUser", "id")



test('Test if FirstPage includes enter lobby button', () => {

    render(<FirstPage/>);
    const textElement= screen.getByText(/Enter Lobby!s/i);
    expect(textElement).toBeInTheDocument();
});

这是我的 index.html:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8"/>
    <link rel="shortcut icon" href="%PUBLIC_URL%/favicon.ico"/>
    <meta
            name="viewport"
            content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <meta name="theme-color" content="#000000"/>

    <!--
      Notice the use of %PUBLIC_URL% in the tags above.
      It will be replaced with the URL of the `public` folder during the build.
      Only files inside the `public` folder can be referenced from the HTML.

      Unlike "/favicon.ico" or "favicon.ico", "%PUBLIC_URL%/favicon.ico" will
      work correctly both with client-side routing and a non-root public URL.
      Learn how to configure a non-root public URL by running `npm run build`.
    -->
    <title>React App</title>
</head>
<body>
<noscript>You need to enable JavaScript to run this app.</noscript>
<div id="root"></div>
<!--
  This HTML file is a template.
  If you open it directly in the browser, you will see an empty page.

  You can add webfonts, meta tags, or analytics to this file.
  The build step will place the bundled scripts into the <body> tag.

  To begin the development, run `npm start` or `yarn start`.
  To create a production bundle, use `npm run build` or `yarn build`.
-->
</body>
</html>

【问题讨论】:

    标签: reactjs typescript create-react-app react-testing-library


    【解决方案1】:

    编辑

    在您的项目上花费了一些时间后,我发现了导致您的测试出现此问题的原因。在FirstPage 使用的某些组件中,您正在像这样导入套接字

    import { socket } from "../.."
    

    这会导致测试中出现意外行为,因为路径错误。

    为了解决这个问题,我从index.tsx 导出套接字并将其放在App.tsx 中,无论您需要在哪里导入它,都可以像这样点亮

    import { socket } from "../../App"
    

    这解决了测试的问题。此外,上面提到的改进仍然适用于更简洁的代码。

    首先,在您的App.tsx 中,您正在导入FirstPage 并将其命名为Greeting,但随后您将在组件中返回FirstPage。您需要返回 Greeting 或将导入重命名为 FirstPage。此外,您需要导入 React 才能使代码正常工作。即使您没有显式使用React,您仍然需要导入它,因为JSX 被转换为使用ReactReact.createElement()

    // App.tsx
    import React, { Component } from "react";
    import FirstPage from "./Component/FirstPage/FirstPage";
    
    export default class App extends Component {
      render() {
        return <FirstPage />;
      }
    }
    
    

    继续您的测试,最好将所有测试放在__tests__ 文件夹中。此外,看起来您实际上也没有导入FirstPage,然后尝试使用它。尝试导入它并使用 App.tsx 中的建议更改再次运行测试。

    // /Components/FirstPage/__tests__/FirstPage.test.tsx
    import React from "react";
    import { render, screen } from "@testing-library/react";
    import FirstPage from '../FirstPage';
    
    test("Test if FirstPage includes enter lobby button", () => {
      render(<FirstPage />);
      ...
    });
    
    

    我已经在代码沙箱中尝试过,并且测试成功了。

    【讨论】:

    • 您好,谢谢您的回答。问候是一个错字,我现在对其进行了编辑。在测试中也导入了 react 和 FirstPage,但仍然失败。
    • 您在 index.tsx 中的 ReactDOM.render 中采用的 ID 属性是否与 index.html@DanielBenedek 中的相同?如果您使用index.html 中的代码编辑您的问题也会很好。
    • 是的,它在这两个地方都是根。除了index.tsx 是'root',index.html 中的 div 是 id="root"。
    • 我在问题中添加了我的index.html
    • @DanielBenedek 你有版本控制系统(例如 GitHub)上的代码吗?然后我就可以在我的本地机器上检查它了。
    猜你喜欢
    • 1970-01-01
    • 2017-02-20
    • 2020-09-28
    • 1970-01-01
    • 2022-10-09
    • 2014-07-19
    • 2014-12-12
    • 1970-01-01
    相关资源
    最近更新 更多