如何测试在该组件中呈现 HOC 或模拟 HOC 的组件?

How to test component that render HOC or mock HOC in that component?

我有一个 HOC 组件。

const SectionComponent = (ComponentToWrap) => {
  return function ComponentToWrapWithLoading({...props}) {
    const { isLoading, isLoaded, icon, title } = props;
    if (!isLoading && isLoaded ) 
      return (
        <div>
          <SectionHeading icon={icon} title={title} />
          <ComponentToWrap {...props} />
        </div>
      );
    if (isLoading) 
      return (<Loader />);
    return null;  
  };
};

export default SectionComponent;

我在 React 组件中使用的:

import React, {Component} from 'react';
import SectionComponent from '../../UI/section/Section'
import { faDumbbell} from '@fortawesome/free-solid-svg-icons';
import TableWrapper from '../../UI/table/Table-wrapper';

const SectionLoadingComponent = SectionComponent(TableWrapper);

export class TrainingsList extends Component {


  componentDidMount() {
    const {fetchTrainings} = this.props;
    fetchTrainings();
  }

  getTableColumns() {
   ...
  }

  render() {
    const { isLoading, isLoaded, data } = this.props.trainings;
    const columns = this.getTableColumns();
    return(
      <div> 
        <SectionLoadingComponent 
          isLoading={isLoading} 
          isLoaded={isLoaded} 
          title='Lista ćwiczeń'
          icon={faDumbbell}
          data={data}
          columns={columns}
          />
      </div>
    );
  }

}

我的问题是我不知道如何在单元测试中模拟 SectionLoadingComponent 我试过使用反应测试渲染器,但组件没有渲染。 如果能提供一些提示和技巧,我将不胜感激。

问题

问题是这一行:

const SectionLoadingComponent = SectionComponent(TableWrapper);

使用此设置无法模拟 SectionLoadingComponent,因为它是在导入 TrainingsList 时计算的,并且它的值始终用于呈现每个实例。即使试图通过模拟 SectionComponent() 来模拟它也无济于事,因为 SectionLoadingComponent 已经在任何模拟代码可以 运行.

时创建

解决方案

不要在 TrainingsList 中调用 SectionComponent(),而是在 Table-wrapper 中调用它并导出结果。

然后直接在TrainingsListrender()中使用Table-wrapper的导出。

使用此设置,您可以在单元测试中模拟 Table-wrapper 的导出,当 TrainingsList 运行 的 render() 时它将使用模拟。