如何模拟更新状态的`onChange`事件

时间:2017-10-03 07:29:42

标签: javascript reactjs unit-testing

我在React写一个应用程序,我用Jest和Enzyme进行单元测试。

我有一个非常简单的组件,它表示一个输入字段,其中包含以下代码:

// 'Container' component definition.
class Container extends React.Component<containerProps, containerState> {
  static defaultProps = { };
  state = {
    hasValue: false
  };

  constructor(props: containerProps) {
    super(props);

    // Bind all the event handlers for the component.
    (this: any).onChange = this.onChange.bind(this);
  }

  onChange(event: MouseEvent) : void {
    this.setState(
      {
        hasValue: (event.target: window.HTMLInputElement).value !== ''
      }
    );

    // Prevent a default browser event from happening.
    event.preventDefault();
  }

  createComponentProps(): componentProps {
    return {
      cssClass: this.createComponentCssClass()
    };
  }

  // Create the CSS class to pass to the component.
  createComponentCssClass(): string {
    let className = '';

    if (this.state.hasValue) { className = className !== '' ? className + 'value' : 'value'; }
    if (this.props.errorMessage && this.props.errorMessage !== '') {
      className = className !== '' ? className + ' error' : 'error';
    }

    // Return the CSS class to apply to the component.
    return className;
  }

  // Renders the 'Container' component.
  render(): React$Element<any> {
    return (
      <Component {...this.createComponentProps()} />
    );
  }
}

所以,这是一个相当简单的组件。 现在,当输入字段的内容发生更改时,会发生状态更改,这会强制将不同的CSS类应用于组件。

我可以确认这是有效的,因为它在浏览器中按预期工作。

现在,我正在编写一个单元测试来验证使用以下代码将className value传递给组件:

it('Passes down the \'cssClass\' property to the \'Input Field\' Component.', () => {
  // Act.
  const wrapper = mount(
    <InputFieldContainer primaryThemeColor="TEAL" accentThemeColor="PINK" useAccentColor={true} />
  );
  wrapper.find('input').simulate('change', { target: { value: 'value' }});
  wrapper.update();

  // Assert.
  expect(wrapper.find(InputFieldComponent).props().cssClass).toEqual('value');
});

因此,我正在渲染组件,我模拟一个更改事件,并检查组件的CSS类属性,但是,它是一个空字符串。似乎没有关于状态变化的更新(但仅在单元测试中)。

在Jest中读取状态,使用console.log(wrapper.state())给我一个JSON对象说hasValue: true,所以状态更新,但即使在调用wrapper.update()之后,CSS类似乎也没有通过了。

我在这里缺少什么?

亲切的问候

1 个答案:

答案 0 :(得分:0)

这似乎与酶(https://github.com/airbnb/enzyme/issues/1153)有关。

更新包装器后,您的组件应该同步。

相关问题