javascript - 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>)
解决方案
由于您所依赖的不仅仅是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'
}
});
推荐阅读
- amazon-cloudformation - 从代码管道中的上一步设置 CodeBuild env var
- html - Flexbox - 特定的定位问题。内容 div 悬停标题
- javascript - 如何解决此错误:“未捕获的 TypeError:无法在“MyClassName”处设置未定义的属性 'borderBottom'”?
- java - 将证书导入 cacerts 在 Mac OS Mojave 上给出文件 I/O 异常
- python-3.x - 如何使用内存分析器逐行分析子进程
- python - 进气目录 - Converter kwarg
- c++ - 访问多态类型,例如不知道确切子类型的变体
- javascript - 如何编写条件来检查页面链接/按钮是否对 click() 可见
- node.js - 快速会话未设置会话
- python - 正则表达式返回部分结果