首页 > 解决方案 > React Typescript 测试 - 目标容器不是 DOM 元素

问题描述

我是测试 React/Typescript 应用程序的新手。

命令(别名react-scripts test):

yarn test

输出:

 FAIL  src/containers/pages/Feature/Feature.test.tsx
  ● Test suite failed to run

    Target container is not a DOM element.

      17 | const { store, persistor } = configureStore(history, initialState);
      18 | 
    > 19 | ReactDOM.render(
         |          ^
      20 |   <Provider store={store}>
      21 |     <PersistGate loading={null} persistor={persistor}>
      22 |       <ConnectedRouter history={history}>

      at Object.render (node_modules/react-dom/cjs/react-dom.development.js:27596:13)
      at Object.render (src/index.tsx:19:10)

简单的测试代码:

import * as React from 'react';
import { create } from 'react-test-renderer';
import Feature from "./Feature";

describe('Feature page component', () => {
  test('matches the snapshot', () => {
    const feature = create(
      <Feature />,
    );
    expect(feature.toJSON()).toMatchSnapshot();
  });
});

src/index.tsx 文件实际上包含ReactDOM.render()在测试中失败的调用,但有什么可行的替代方法?

注意:应用程序本身运行良好,只是无法在测试模式下运行。


在 src/index.tsx 文件中我有:

export const history = createBrowserHistory({
  basename: '/admin',
});
const initialState: StoreState = (undefined as unknown) as StoreState;
const { store, persistor } = configureStore(history, initialState);

然后在服务和传奇中,我historystoreindex.tsx 导入。可能是导致测试失败的问题吗?


我试图提取history并保存store到一个单独的文件中(如评论者所建议的那样)。现在上面的代码在里面src/initialState.ts

标签: reactjstypescriptreact-test-renderer

解决方案


现在在您的测试中发生的问题是您想要测试一个从index.tsx. 当您的 import fromindex.tsx ReactDOM.render也被调用并且您的测试失败时。

确保不要从index.tsx单独的文件中导入和移动您在那里定义的逻辑。

通常,您的应用程序会有一个索引文件,例如:index.tsx它导入您的App.tsx并且只关心将 React 组件渲染到带有ReactDOM.render.

在中,App.tsx您将定义所有组件,例如Provider, PersistGate, 甚至Feature

当你测试你的组件时,你要确保它不ReactDOM.render包含ReactDOM.render

我提供了一个示例,说明如何在代码盒中设置类似的内容

现在我更喜欢使用@testing-library/react测试组件,而不是react-test-renderer它也成为默认的测试库create-react-app


推荐阅读