代码之家  ›  专栏  ›  技术社区  ›  Chris Farmer Marcelo Cantos

为什么我的酶测试中没有运行onChange回调?

  •  0
  • Chris Farmer Marcelo Cantos  · 技术社区  · 6 年前

    我有一个简单的React包装器组件,它围绕着一个material ui TextField .我正在尝试使用酶和 simulate 在我的组件中处理的底层文本字段上触发事件,使用 shallow 使用 mount 我不明白。当我试图模拟 keyup 事件处理程序使用shallow或mount,按预期运行。当我试图模拟 change 事件中,mount case似乎什么都没有发生,但在使用shallow时它似乎有效。

    在下面的示例测试中,我希望看到两个事件处理程序的控制台输出,但在使用mount的情况下,我没有看到change事件的输出。我知道在这个特定的情况下我不需要在这里使用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
    })
    
    
    
    0 回复  |  直到 6 年前
        1
  •  0
  •   Drew Reese    6 年前

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

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