我有一个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 我尝试过使用react test-renderer,但是组件没有渲染。 我将非常感谢您提供一些提示和技巧。
答案 0 :(得分:1)
问题
问题是这一行:
const SectionLoadingComponent = SectionComponent(TableWrapper);
使用此设置,无法模拟SectionLoadingComponent
,因为它是在导入TrainingsList
时进行评估的,并且其值始终用于呈现每个实例。即使尝试通过模拟SectionComponent()
来模拟它,也没有任何作用,因为SectionLoadingComponent
已经在任何模拟代码可以运行的时候就已经创建。
解决方案
与其在SectionComponent()
中调用TrainingsList
,而在Table-wrapper
中调用它并导出结果。
然后直接在Table-wrapper
的{{1}}中使用render()
的导出。
通过此设置,您可以在单元测试中模拟TrainingsList
的导出,并且当Table-wrapper
的{{1}}运行时将使用该模拟。