当我尝试通过模拟事件对象传递值时遇到问题。 我收到错误:
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>
(...)
测试本身:
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/