【发布时间】:2018-02-06 21:18:49
【问题描述】:
在我要测试的组件中,我从父组件导入了几个组件:
import {
ResponsiveContainer,
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Legend,
} from 'recharts';
如何只模拟 ResponsiveContainer 而不触及其他组件?
更新:Dennie de Lange 在这种情况下提示使用依赖注入。完全同意。但是我遇到了以下问题。这是我的组件:
import React, { Component } from 'react';
import {
ResponsiveContainer,
LineChart,
} from 'recharts';
import moment from 'moment';
class CustomLineChart extends Component<Props> {
render() {
const { data, container: Container = ResponsiveContainer } = this.props;
if (!data) return null;
return (
<div className="lineChart">
<Container>
<LineChart data={data}>
... lots of other stuff here
</LineChart>
</Container>
</div>
);
}
}
export default CustomLineChart;
这是我的测试:
const Mock = ({ children }) => <div>{children}</div>;
describe('<LineChart />', () => {
it('renders data if provided', () => {
const component = create(<LineChart data={data} container={Mock} />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
这是我为此获得的快照:
<div
className="lineChart"
>
<div />
</div>
所以Container 的孩子由于某种原因失踪了。有什么想法吗?
更新 2:实际上上面的实现是正确的,这是 LineChart 在我的情况下没有渲染任何东西。
【问题讨论】: