【发布时间】: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