开玩笑地用事件对象和值模拟('click')酶

时间:2018-06-28 11:11:12

标签: javascript reactjs redux jestjs enzyme

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

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

我见过https://docs.cypress.io/guides/guides/continuous-integration.html#Example-circle-yml-v2-config-file-with-yarn,但是我需要传递如下创建的整个事件对象:

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

1 个答案:

答案 0 :(得分:3)

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

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

编辑:如果您需要任何默认事件行为,则可以添加虚拟函数来代替它们(或者如果要测试它们是否真正被调用,还可以添加模拟函数)。例如

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