【问题标题】:How to pass props into jest test in React如何在 React 中将 props 传递给 jest 测试
【发布时间】:2019-04-06 04:05:51
【问题描述】:

我是 React 和测试的新手。我正在尝试测试具有条件渲染的组件:

render() {
if (this.props.fetched === true){
  return (
    <div className="search">
      <div className="">
        <SearchBar getCountry={this.getCountry} /> <br/>
        <Results country={this.props.country}/>
      </div>
    </div>
  );
} else { return (
    <div className="search">
      <div className="">
        <SearchBar getCountry={this.getCountry} /> <br/>
      </div>
    </div>
)}

} }

在我的测试中,我试图将 this.props.fetched 传递到包装器中以测试在 fetched=true 之后显示的内容。现在这是我的测试:

it('renders results after search', () => {
  const fetched = true;
  const wrapper = shallow(<Search store={store} {...fetched}/>);
  expect(wrapper.find('Results').length).toEqual(1);
});

但是我的测试一直失败,所以我不能传递道具。这样做的正确方法是什么?谢谢!

【问题讨论】:

    标签: reactjs jestjs enzyme


    【解决方案1】:
    it('renders results after search', () => {
      const fetched = true;
      const wrapper = mount(<Search store={store} {...fetched}/>);
      expect(wrapper.find('Results').length).toEqual(1);
    });
    

    使用 mount 而不是 shallow 应该可以解决您的问题。或者您也可以尝试使用wrapper.update() 保留shallow(我不确定)。

    财政年度:Diff between Shallow and Mount

    【讨论】:

    • mount 让我的控制台日志显示为真,但不会使条件渲染语句显示我的结果组件
    【解决方案2】:
    it('renders results after search', () => {
      const fetched = true;
      const wrapper = shallow(<Search store={store} fetched={fetched} />);
      expect(wrapper.find('Results').length).toEqual(1);
    });
    

    那么你可以做同样的事情,要么省略 fetched 要么设置为 false

    【讨论】:

    • 这对我也不起作用,而且我确实对没有道具的初始状态进行了测试,这有效
    • 这是传递道具的正确方法。问题很可能是找到Results - 请记住您的渲染很浅,因此组件不会完全渲染。
    • @peter176 在测试中,你可以做一个console.log(wrapper.prop('fetched')) 来确保获取的道具是正确的
    • true - 您也可以使用const res = wrapper.find('Results') 并注销。尝试不带引号的Results。它不是一个字符串,它是一个组件——还要确保你将它导入到测试中
    • @bsapaka 道具是假的,这就解释了。如何正确传递它?
    猜你喜欢
    • 1970-01-01
    • 2021-07-19
    • 1970-01-01
    • 2019-08-11
    • 2022-11-17
    • 2021-05-06
    • 1970-01-01
    • 2020-04-10
    • 2023-03-08
    相关资源
    最近更新 更多