Reactjs 如何测试渲染

Reactjs 如何测试渲染,reactjs,enzyme,Reactjs,Enzyme,如何编写检查渲染元素的测试?例如,类似这样的组件,其渲染取决于现有卡片列表: class ButtonMore extends Component { render() { if (!this.props.listCards.length) { return null; } return ( <button onClick={this.props.onClick} className="buttons button-more">

如何编写检查渲染元素的测试?例如,类似这样的组件,其渲染取决于现有卡片列表:

class ButtonMore extends Component {
  render() {
    if (!this.props.listCards.length) {
      return null;
    }
    return (
      <button onClick={this.props.onClick} className="buttons button-more">
        More
      </button>
    );
  }
}
class按钮更多扩展组件{
render(){
if(!this.props.listCards.length){
返回null;
}
返回(
更多
);
}
}
如何检查渲染依赖于道具

function setup() {
  const props = {
    listCards: [1, 2]
  };
  const wrapper = shallow(
    <Provider store={store}>
      <ButtonMore {...props} />
    </Provider>
  );
  return {
    props,
    wrapper
  };
}

describe("ButtonMore component", () => {
  const { wrapper } = setup();
  it("should render button if cards length more then 0", () => {
    expect(wrapper.prop("listCards").length).toBe(2); // that's ok
    expect(wrapper.find("button").length).toBe(1); // received 0, not 1
  });
});
函数设置(){
常量道具={
列表卡:[1,2]
};
常数包装=浅(
);
返回{
道具,
包装纸
};
}
描述(“按钮更多组件”,()=>{
const{wrapper}=setup();
它(“如果卡片长度超过0,则应渲染按钮”,()=>{
expect(wrapper.prop(“listCards”).length.toBe(2);//没关系
expect(wrapper.find(“button”).length.toBe(1);//收到的是0,不是1
});
});
不幸的是,我没有在酶文档中找到解决方案。

首先:“!this.props.listCards.length”只检查listCards是否具有属性length。您必须确保listCards是一个数组,并且长度大于0

现在确保包装器包含正确的数据:您可以使用console.log(wrapper.debug())来完成

最后。。如果你不需要商店,你甚至不能使用提供商。只渲染按钮更多,并将onClick和listcard作为道具传递