【问题标题】:Enzyme / Jest spies not called onClick酶 / Jest 间谍未调用 onClick
【发布时间】:2019-01-12 00:32:55
【问题描述】:

我正在尝试使用 Enzyme / Jest 为反应组件测试事件处理程序,但是我的 spy 函数从未被调用...

我的组件有一个带有 id 的 div,我正在使用它来查找 dom elem

 render() {
    return (
        <div>
            <Top
                {...this.props}
            />
            <div 
                id = 'keyboard_clickable'
                onClick = {this._handleClick}
                style= {styles.main}>
                {this._showKeyBoard()}
            </div>
            <input onChange = {() => {}}/>
      </div>
    );
  }
}

我的测试

describe('onclick function is called ...', () => {
  it.only('spyOn', () => {
    const spy = jest.fn()

    const wrapper = shallow(
      <Keyboard 
      _getData      = { () => {} }
      _erase        = { () => {} }
      _get_letters  = { () => {} }
      _createWord   = { () => {} }
      _modeSwitch   = { () => {} }
      onClick       = { spy      }
      />
    )

    wrapper.find('#keyboard_clickable').simulate('click', {
      target:{
        parentElement:{ id: 5 },
        id:6
        }
    })
    expect(spy).toHaveBeenCalled();

  })
})

我的 HandleClick

_handleClick = e => {
    let parent = e.target.parentElement;
    if(e.target.id || (!isNaN(parent.id) && parent.id > 0) ) {
        this.props._getData(e.target.id || e.target.parentElement.id)
        this.setState({status:'ok'})
    }else{
        this.setState({status:'Use numbers between 2 and 9'},()=>{
            return alert(this.state.status)
        })

    }
}

测试输出

Expected mock function to have been called, but it was not called.

【问题讨论】:

  • 能否请您展示一下 Keyboard._handleClick 的作用?我怀疑它可能没有调用 Keyboard.props.onClick。
  • 是的不是调用Keyboard.props._handleClick,方法是Keyboard._handleClick
  • 请将其添加到您的原始帖子中,此处几乎无法阅读
  • 您的 _handleClick 方法从不调用 onClick 道具。您可以测试的是状态是否正确更改并且 _getData 道具被调用

标签: reactjs testing jestjs enzyme


【解决方案1】:

要测试您的事件处理程序是否被调用,您必须将事件处理程序替换为模拟函数。一种方法是扩展您的组件类:

class TestKeyboard extends Keyboard {
  constructor(props) {
    super(props)
    this._handleClick = this.props._handleClick
  }
}

describe('onclick function is called ...', () => {
  it.only('spyOn', () => {
    const spy = jest.fn()

    const wrapper = shallow(
      <TestKeyboard 
      _getData      = { () => {} }
      _erase        = { () => {} }
      _get_letters  = { () => {} }
      _createWord   = { () => {} }
      _modeSwitch   = { () => {} }
      _handleClick  = { spy      }
      />
    )

    wrapper.find('#keyboard_clickable').simulate('click', {
      target:{
        parentElement:{ id: 5 },
        id:6
        }
    })
    expect(spy).toHaveBeenCalled();

  })
})

道具_handleClick 替换了Keyboard._handleClick,因此当onClick 在被点击的元素中触发时被调用。

或者,jest.spyOn

如果您需要让事件处理程序执行测试它被调用的内容,您可以使用jest.spyOn。我发现这种方法更复杂,但更灵活。

import { mount } from 'enzyme'

describe('onclick function is called ...', () => {
  it.only('spyOn', () => {
    const wrapper = mount(
      <Keyboard 
      _getData      = { () => {} }
      _erase        = { () => {} }
      _get_letters  = { () => {} }
      _createWord   = { () => {} }
      _modeSwitch   = { () => {} }
      />
    )

    const spy = jest.spyOn(wrapper.instance(), '_handleClick')
    wrapper.instance().forceUpdate()

    wrapper.find('#keyboard_clickable').simulate('click', {
      target:{
        parentElement:{ id: 5 },
        id:6
        }
    })
    expect(spy).toHaveBeenCalled();

  })
})

请注意,当使用浅层渲染时这会失败,因此您必须改用酶安装。

【讨论】:

  • 感谢确实通过了测试!
  • 我缺少 wrapper.instance().forceUpdate(),谢谢
【解决方案2】:

似乎在浅层渲染中使用酶模拟点击确实有效,但前提是我强制更新(),就像在 Jemi 的解决方案中一样。

示例:

 beforeEach(() => {
    wrapper = shallow(<VehicleDamage handleSubmit={mockFunction} onPrevClick={mockFunction} />);
});

it('handlePrevClick is called on click', function() {
    const spyHandlePrevClick = jest.spyOn(wrapper.instance(), 'handlePrevClick');
    wrapper.instance().forceUpdate(); // I assume required to assign mocked function

    let buttonContainer = wrapper.find('ButtonContainer').dive();
    let button = buttonContainer.find('Button').at(0);

    button.simulate('click', {
        preventDefault: () => jest.fn()
    });

    expect(spyHandlePrevClick).toHaveBeenCalled();
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-07-21
    • 2021-09-24
    • 2015-08-29
    • 2019-04-21
    • 2021-07-27
    • 2017-04-04
    • 2018-09-28
    • 2019-11-18
    相关资源
    最近更新 更多