【问题标题】:Jest: mock one of several exported components笑话:模拟几个导出的组件之一
【发布时间】: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 在我的情况下没有渲染任何东西。

【问题讨论】:

    标签: reactjs mocking jestjs


    【解决方案1】:

    通过在您要测试的组件中使其可配置?

    const MyTestComponent = ({container:Container=ResponsiveContainer}) => ...
    

    这允许您创建一个模拟并将其提供给MyTestComponent

    【讨论】:

    • 我很想找到一种用玩笑来模拟它的方法,忘记了依赖注入 :) 谢谢提醒。但我仍然无法完成它。我已经尝试过您的解决方案并将const Mock = ({ children }) =&gt; &lt;div&gt;{children}&lt;/div&gt;; 提供给container 道具,但我只得到&lt;div /&gt; 作为快照。有什么想法吗?
    • 这可能取决于组件,如果没有看到更多实现,真的不能说
    • 我已经添加了实现细节。
    • 您是否尝试过附加一个简单的孩子并查看结果?看起来 LineChart 没有渲染.. 所以试试
      test
    猜你喜欢
    • 2018-07-27
    • 2019-11-24
    • 2021-09-19
    • 1970-01-01
    • 1970-01-01
    • 2021-12-11
    • 1970-01-01
    • 2019-08-20
    • 2016-08-30
    相关资源
    最近更新 更多