reactjs - 为什么酶浅层组件和安装组件之间的 onChange 事件不同?
问题描述
我在 material-ui 周围有一个简单的 React 包装器组件TextField
。我正在尝试使用酶并触发在我的组件中处理的底层 TextField 上的事件,并且使用和使用之间存在我不理解simulate
的行为差异。当我尝试使用浅层或挂载来模拟事件时,事件处理程序会按预期运行。当我尝试模拟一个事件时,安装情况似乎没有发生任何事情,但是在使用浅层时它似乎可以工作。shallow
mount
keyup
change
在下面的示例测试中,我希望看到两个事件处理程序的控制台输出,但在我使用 mount 的情况下,我看不到 change 事件的输出。我知道在这种特定情况下我不需要在这里使用 mount,但我想在我确实需要 mount 的情况下了解这种行为。
mount
使用ed 组件时如何正确触发我的更改事件?
import React from 'react'
import { mount, shallow } from 'enzyme'
import TextField from '@material-ui/core/TextField'
const MyTextField = (props: any) => {
const handleChange = (e: any) => {
console.log('in handleChange')
}
const handleKeyUp = (e: any) => {
console.log('in handleKeyUp')
}
return <TextField onChange={handleChange} onKeyUp={handleKeyUp} />
}
it('should do something', () => {
const shallowWrapped = shallow(<MyTextField />)
shallowWrapped.find(TextField).simulate('keyup', {}) // "in handleKeyUp" output to console
shallowWrapped.find(TextField).simulate('change', { target: { value: 'test' } }) // "in handleChange" output to console
const mountWrapped = mount(<MyTextField />)
mountWrapped.find(TextField).simulate('keyup', {}) // "in handleKeyUp" output to console
// The below line doesn't seem to work as I expect...
mountWrapped.find(TextField).simulate('change', { target: { value: 'test' } }) // nothing is output to console
})
解决方案
根据 Enzyme 的这个Common-Gotchas,您需要提供一个模拟事件对象,该对象具有回调中使用的属性,这些属性不包含在SyntheticEvent
.
it('should do something', () => {
wrapped = mount(<MyTextField />);
wrapped.find(TextField).simulate('keyup', {});
wrapped.find(TextField).simulate('change', { target: { value: 'test' } });
});
推荐阅读
- android - Lateinit 属性 viewModel 尚未初始化
- python - 范围内的 Python 编号
- python - VS Code“在终端中运行 Python”播放按钮不起作用
- sql - 根据另一个表 Firebird 的数据将 MERGE 语句合并到表中
- c# - c# wpf 打印后将 Canvas 添加回 Border
- machine-learning - InvalidArgumentError:不兼容的形状:[15,3] 与 [100,3]
- javascript - TypeError:没有'new'就不能调用类构造函数MongoStore
- javascript - 当我尝试确保我的 JavaScript 代码正常工作时,我在 Google Chrome 上的控制台上收到此错误
- npm - 将“date-fns”导入 Svelte 模块时出错
- three.js - Aframe/Three/WebXR:在 VR 模式下禁用设备方向