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

问题描述 投票:1回答:1

我有一个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;

我在反应组件中使用:

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我试图使用react test-renderer,但组件没有渲染。我会非常感谢一些提示和技巧。

reactjs unit-testing mocking jestjs higher-order-components
1个回答
1
投票

问题

问题是这一行:

const SectionLoadingComponent = SectionComponent(TableWrapper);

使用此设置,无法模拟SectionLoadingComponent,因为在导入TrainingsList时会对其进行求值,并且其值始终用于渲染每个实例。即使试图通过模拟SectionComponent()来模拟它也没有任何作用,因为任何模拟代码都可以运行时已经创建了SectionLoadingComponent

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

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

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

© www.soinside.com 2019 - 2024. All rights reserved.