首页 > 解决方案 > Enzyme – 测试需要任意 `target` 属性的事件处理函数

问题描述

免责声明:我使用Preact作为库和enzyme-adapter-preact-pure酶的适配器。


我写了以下函数:

function handleInputChange(e) {
  const target = e.target,
    value = target.type === 'checkbox' ? target.checked : target.value;
  this.setState({ [target.name]: value });
}

这个函数是独立的,它打算在 React 的 Component 实例中使用,如下所示:

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      name: null
    };

    this.handleInputChange = handleInputChange.bind(this);
  }

  render() {
    return <input name="name" onChange={this.handleInputChange} />;
  }
}

这样我就不需要在每个需要处理输入更改的组件上重新实现它。

问题:

由于我依赖event.target它的属性,我不知道如何用酶对其进行测试,因为我无法target按照我的意愿设置和那些属性:

// Test file
// Consider `wrapper` as an instance of `App` shown above, mounted with Enzyme's `mount` function.

test('it changes the correspondent state key when input is changed', () => {
  wrapper.find('input').simulate('change', { target: { value: 'foo', name: 'name' } });
  expect(wrapper.state('name')).toEqual('foo');
});

尝试这样做会引发错误:TypeError: Cannot set property target of [object Event] which has only a getter at Function.assign (<anonymous>)

标签: javascriptreactjsjestjsenzymepreact

解决方案


由于您所依赖的不仅仅是target.value您还需要通过涵盖所有基础的适当模拟。

下面的代码应该解决它。

wrapper.find('input').simulate('change', {
  target: {
    value: 'foo',
    name: 'name',
    checked: true,
    type: 'checkbox'
  }
});

// OR

// In this case there will be no checkbox found and this it wont look for checked value present or not
wrapper.find('input').simulate('change', {
  target: {
    value: 'foo',
    name: 'name'
  }
});

推荐阅读