【问题标题】:With Enzyme, how can I test changing the number of children?使用 Enzyme,我如何测试改变孩子的数量?
【发布时间】:2017-09-13 17:43:57
【问题描述】:

我有一个<Parent/> 组件,当我添加/删除/更改它的<Child/> 组件时,我想使用 Enzyme 来测试它的行为。例如,改变

<Parent>
  <Child />
</Parent>

<Parent>
  <Child />
  <Child />
</Parent>

我正在使用操作 DOM 的第 3 方库,因此我需要跟踪子项以使 React 和库保持同步。

我尝试多次调用mount,尽管两个mount 调用创建了两个不同的实例。例如,

let constructorCalls = 0;
let Parent = class extends React.Component {
  constructor(props) {
    super(props);
    constructorCalls += 1;
  }
  render() { return <span />; }
}

mount(<Parent />);
mount(<Parent />);

// Now, constructorCalls = 2

调用mount 两次会创建两个不同的父级和两个不同的构造函数调用,因此它的行为不像 React 那样,如果渲染的组件没有改变,它什么也不做。

那么,如何使用 Enzyme “重新安装”具有不同子级的组件?

【问题讨论】:

  • 当事件被触发(例如 onClick)时,您的子组件不会发生变化吗?

标签: reactjs enzyme


【解决方案1】:

我仍然找不到 Enzyme 的答案,所以这里有一个 Enzyme-ish 解决方案。

它不喜欢 Enzyme 有这个功能,所以我通过内联一个包装器组件来完成它,并通过将 props 传递给包装器来更改子组件的数量。 (注意我使用的是 ES6 类)

const WrapperComponent = class extends React.Component{
  static defaultProps = {
    n: 1
  }
  render() {
    if (this.props.n > 1) {
      return (
        <Parent>
          <Child />
          <Child />
        </Parent>
      );
    }
    return (
      <Parent>
        <Child />
      </Parent>
    );
  }
}

const wrapper = mount(<WrapperComponent/>);

// ... test the state of Parent with one child

wrapper.setProps({ n: 2});

// ... test the state of Parent with two children

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-25
    • 2018-11-09
    • 1970-01-01
    • 2018-07-15
    • 2021-01-31
    • 1970-01-01
    相关资源
    最近更新 更多