为什么onChange事件在浅层和固定组分之间不同?

问题描述 投票:0回答:1

我在material-ui TextField周围有一个简单的React包装器组件。我正在尝试使用酶和simulate触发在组件中处理的基础TextField上的事件,并且使用shallow和使用mount之间存在行为差异,我不理解。当我尝试使用浅层或挂载模拟keyup事件时,事件处理程序将按预期运行。当我尝试模拟change事件时,挂载情况似乎什么也没有发生,但是在使用浅表时似乎可以使用。

在下面的示例测试中,我希望看到两个事件处理程序的控制台输出,但是在使用mount的情况下,我看不到change事件的输出。我知道在这种特定情况下不需要在这里使用mount,但是我想在需要安装的情况下了解此行为。

使用mount ed组件时如何正确触发变更事件?

import React from 'react'
import { mount } 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
})


reactjs jestjs enzyme
1个回答
0
投票

根据来自Enzyme的Common-Gotchas,您需要提供一个模拟事件对象,该对象具有回调中使用的SyntheticEvent中未包含的属性。

it('should do something', () => {
  wrapped = mount(<MyTextField />);
  wrapped.find(TextField).simulate('keyup', {});
  wrapped.find(TextField).simulate('change', { target: { value: 'test' } });
});
© www.soinside.com 2019 - 2024. All rights reserved.