首页 > 解决方案 > 为什么酶浅层组件和安装组件之间的 onChange 事件不同?

问题描述

我在 material-ui 周围有一个简单的 React 包装器组件TextField。我正在尝试使用酶并触发在我的组件中处理的底层 TextField 上的事件,并且使用和使用之间存在我不理解simulate的行为差异。当我尝试使用浅层或挂载来模拟事件时,事件处理程序会按预期运行。当我尝试模拟一个事件时,安装情况似乎没有发生任何事情,但是在使用浅层时它似乎可以工作。shallowmountkeyupchange

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

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

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


标签: reactjsjestjsenzyme

解决方案


根据 Enzyme 的这个Common-Gotchas,您需要提供一个模拟事件对象,该对象具有回调中使用的属性,这些属性不包含在SyntheticEvent.

it('should do something', () => {
  wrapped = mount(<MyTextField />);
  wrapped.find(TextField).simulate('keyup', {});
  wrapped.find(TextField).simulate('change', { target: { value: 'test' } });
});

推荐阅读