React Typescript 测试 - 目标容器不是 DOM 元素

naX*_*aXa 6 typescript reactjs react-test-renderer

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

命令(别名react-scripts test):

yarn test
Run Code Online (Sandbox Code Playgroud)

输出:

 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)
Run Code Online (Sandbox Code Playgroud)

简单的测试代码:

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();
  });
});
Run Code Online (Sandbox Code Playgroud)

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);
Run Code Online (Sandbox Code Playgroud)

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


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

  • 好消息:错误“目标容器不是 DOM 元素”消失了!
  • 坏消息:我收到一个新错误(这可能是一个独立的问题,所以提取到一个单独的问题

tak*_*ake 3

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

确保不要index.tsx从单独的文件中导入任何内容,也不要移动您在其中定义的逻辑。

一般来说,您的应用程序会有一个索引文件,例如:index.tsx它导入您的App.tsx应用程序并且只关心使用ReactDOM.render.

在 中App.tsx,您可以定义所有组件,例如ProviderPersistGate,甚至Feature

当您测试组件时,您需要确保它不包含ReactDOM.render,因为测试时您所做的就是在虚拟 dom 内渲染被测组件,不幸的是,这与ReactDOM.render

我提供了一个关于如何在codesandbox中设置类似内容的示例

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