如何在 React 中将 props 传递给 Jest 测试

pet*_*176 5 reactjs jestjs enzyme

我是 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>
)}
Run Code Online (Sandbox Code Playgroud)

} }

在我的测试中,我试图将 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);
});
Run Code Online (Sandbox Code Playgroud)

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

jsw*_*324 3

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

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