【问题标题】:How to test component that render HOC or mock HOC in that component?如何测试在该组件中呈现 HOC 或模拟 HOC 的组件?
【发布时间】:2019-01-27 01:30:19
【问题描述】:

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

    问题

    问题是这一行:

    const SectionLoadingComponent = SectionComponent(TableWrapper);

    使用此设置无法模拟 SectionLoadingComponent,因为它是在导入 TrainingsList 时评估的,并且它的值始终用于渲染每个实例。即使尝试通过模拟 SectionComponent() 来模拟它也无济于事,因为在任何模拟代码可以运行时已经创建了 SectionLoadingComponent

    解决方案

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

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

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

    【讨论】:

    • 是的,那是:),在导出类时也有一个错误,不是默认的。
    猜你喜欢
    • 1970-01-01
    • 2019-07-04
    • 2018-11-24
    • 2019-12-22
    • 2017-06-03
    • 2021-04-18
    • 1970-01-01
    • 2019-09-30
    • 2019-12-19
    相关资源
    最近更新 更多