【问题标题】:Jest fails because Target container is not a DOM elementJest 失败,因为 Target 容器不是 DOM 元素
【发布时间】:2022-01-13 12:32:30
【问题描述】:

我正在尝试以开玩笑的方式在 React 应用程序上运行组件测试,但由于以下错误而失败。但是应用程序运行正常

 FAIL  src/__tests__/app.test.tsx
  ● Test suite failed to run

    Target container is not a DOM element.

       7 | import reportWebVitals from './reportWebVitals';
       8 |
    >  9 | ReactDOM.render(
         |          ^
      10 |     <React.StrictMode>
      11 |         <Provider store={store}>
      12 |             <App />

      at Object.render (node_modules/react-dom/cjs/react-dom.development.js:26091:13)
      at Object.<anonymous> (src/index.tsx:9:10)
      at Object.<anonymous> (src/App.tsx:6:1)
      at Object.<anonymous> (src/__tests__/app.test.tsx:45:1)

这是我的 App.tsx 文件。

import React from 'react';
import 'reflect-metadata';
import { BrowserRouter, Switch } from 'react-router-dom';
import { Message } from '@library/queues';

const App: React.FC = () => {
   return (
     <ThemeProvider theme={'dark'}>
      // routes
     </ThemeProvider>
   )}

export default App;

这是索引文件

import React from 'react';
import ReactDOM from 'react-dom';
import './index.scss';
import App from 'App';
import { Provider } from 'react-redux';
import store from 'redux/store';
import reportWebVitals from './reportWebVitals';

ReactDOM.render(
    <React.StrictMode>
        <Provider store={store}>
            <App />
        </Provider>
    </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))
reportWebVitals();

最后是测试文件

import React from 'react';
import { render, screen } from '@testing-library/react';
import App from './App';

test('renders learn react link', () => {
    render(<App />);
    const linkElement = screen.getByText(/learn react/i);
    expect(linkElement).toBeInTheDocument();
});

我已经验证了许多链接并尝试了不同的方法,但都只会导致此错误。我正在使用一个私有 npm 模块并使用 moduleNameMappers 映射它,有时这也会引发错误。

moduleNameMapper: {
        '^@library/queues(.*)$': '<rootDir>/src/$1', -- working without errors but throwing errors when we run tests
        // '^@library/queues(.*)$': '<rootDir>/node_modules/$1', -- throwing errors
        '\\.(css|scss|jpg|png)$': '<rootDir>/empty-mock-module.js',
    },

无论我做对与否,有人可以帮助我吗?我需要知道如何在代码中映射 node_modules 库。除了我的私有模块之外,所有的 npm 模块都在工作。

【问题讨论】:

    标签: javascript reactjs typescript jestjs


    【解决方案1】:

    当应用程序在 Jest 中呈现时,它找不到“根”元素,所以我找到的一种解决方案是在“根”不存在时提供一个 div 元素。

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-01-13
      • 2019-12-17
      • 2021-06-04
      • 2018-04-24
      • 1970-01-01
      • 2022-08-17
      • 2019-01-16
      相关资源
      最近更新 更多