我有一个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,但组件没有渲染。我会非常感谢一些提示和技巧。
问题
问题是这一行:
const SectionLoadingComponent = SectionComponent(TableWrapper);
使用此设置,无法模拟SectionLoadingComponent
,因为在导入TrainingsList
时会对其进行求值,并且其值始终用于渲染每个实例。即使试图通过模拟SectionComponent()
来模拟它也没有任何作用,因为任何模拟代码都可以运行时已经创建了SectionLoadingComponent
。
解
而不是在SectionComponent()
中调用TrainingsList
,在Table-wrapper
中调用它并导出结果。
然后直接在Table-wrapper
的render()
中使用TrainingsList
的导出。
使用此设置,您可以在单元测试中模拟Table-wrapper
的导出,当render()
运行时,它将使用模拟。