【问题标题】:jest enzyme simulate('click') with event object and value带有事件对象和值的笑话酶模拟(“点击”)
【发布时间】:2018-12-07 10:47:50
【问题描述】:

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

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())
  })

【问题讨论】:

    标签: javascript reactjs redux jestjs enzyme


    【解决方案1】:

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

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

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

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

    【讨论】:

    • 这样做我得到错误:TypeError: event.stopPropagation is not a function at SingleSymbol.handleLotChange.event [as handleLotChange] (src/containers/SingleSymbol.js:94:13) at onClick (src /containers/SingleSymbol.js:145:40)
    • 您需要手动向对象添加 stopPropagation 函数。已编辑我的答案以包含一个示例。
    • 有没有办法在模拟事件对象中设置currentTarget?我设置它的方式与上面的 target 属性相同,但它没有被事件处理程序拾取。
    猜你喜欢
    • 1970-01-01
    • 2018-11-10
    • 2018-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2021-09-07
    • 2018-11-05
    相关资源
    最近更新 更多