gpt4 book ai didi

javascript - jest enzyme 模拟 ('click' ) 与事件对象和值

转载 作者:行者123 更新时间:2023-11-30 09:22:00 24 4
gpt4 key购买 nike

当我尝试通过具有值的模拟事件对象传递时遇到问题。我收到错误:

TypeError: Cannot read property 'value' of null

at SingleSymbol.handleLotChange.event [as handleLotChange] (src/containers/SingleSymbol.js:95:46)
at onClick (src/containers/SingleSymbol.js:145:40)
at node_modules/enzyme-adapter-react-16/build/ReactSixteenAdapter.js:332:27

我看过case但是我需要传递如下创建的整个事件对象:

const event = new Event('click', {"target":{"value":8}})

因为在处理“点击”事件的函数中我使用了 stopPropagation 函数

handleLotChange = (event) => {
event.stopPropagation()
this.setState({lotValue: event.target.value})
}

测试组件的片段:

(...)
<Grid item xs={4} >
<TextField
label="Lot"
id="lot-value"
value={this.state.lotValue}
onChange={(event) => this.handleLotChange(event)}
onClick={(event) => this.handleLotChange(event)}
type="number"
className={classes.lotGrid}
InputLabelProps={{
shrink: true,
}}
inputProps={{ min: "0", max: "10", step: "0.01" }}
/>
</Grid>
(...)

self 测试:

  it('captures inserted Lot value', () => {
const event = new Event('click', {"target":{"value":8}})
const wrapper = shallow(<SingleSymbol data={dummy} classes={styles(theme)} />)
wrapper.find('WithStyles(Paper)').simulate('click')
wrapper.find('#lot-value').simulate('click', event)
console.log(wrapper.state())
})

最佳答案

您不需要将实际事件传递给simulate,您只需传递一个带有处理函数所需数据的普通对象即可。所以你可以这样做:

wrapper.find('#lot-value').simulate('click', {"target":{"value":8}})

编辑:如果您需要任何默认事件行为,您可以添加虚拟函数来代替它们(如果您想测试它们是否被实际调用,甚至可以模拟)。例如

wrapper.find('#lot-value').simulate('click', {
target: { value: 8 },
stopPropagation: () => {},
})

关于javascript - jest enzyme 模拟 ('click' ) 与事件对象和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51081424/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com