首页 > 解决方案 > onClick Jest / 酶:方法“模拟”意味着在 1 个节点上运行。找到了 0 个

问题描述

我无法测试以下代码的 onClick。我不断收到以下错误:

Method “simulate” is meant to be run on 1 node. 0 found instead.

我的组件代码如下所示:

constructor (props) {
  super(props)
  this.state = INITIAL_STATE;
}

handleQuickFilter = (type) => {
  this.setState({
    quickFilterObj: {...this.state.quickFilterObj, [type]: {...this.state.quickFilterObj[type], checked: !this.state.quickFilterObj[type].checked}}
    }, () => {
      let filter = this.buildFilter();
      filter ? 
        linker.UniversalGrid('Counterparty.Loa.Enrollment', '', `{form_filter}=$filter=(${filter}),{grid_selectable}=1,{can_add}=1`) 
      :
        linker.UniversalGrid('Counterparty.Loa.Enrollment', '', `{form_filter}='',{grid_selectable}=1,{can_add}=1`)
  })
}

render () {
  return(
    <div className='enrollment-grid-wrapper'>   
      <div className='quick-filter-div'>
        <button className={this.state.quickFilterObj['New'] && this.state.quickFilterObj['New'].checked ? 'checked quick-filter' : 'unchecked quick-filter'} 
                id = 'testnew'
                onClick={() => {this.handleQuickFilter('New')}}
                >
            New {this.state.quickFilterObj['New'] && this.state.quickFilterObj['New'].count !== undefined ? `(${this.state.quickFilterObj['New'].count})` : null}
        </button>
        <button className={this.state.quickFilterObj['Sent'] && this.state.quickFilterObj['Sent'].checked ? 'checked quick-filter' : 'unchecked quick-filter'} 
                onClick={()=>{this.handleQuickFilter('Sent')}}
                >
            Sent {this.state.quickFilterObj['Sent'] && this.state.quickFilterObj['Sent'].count !== undefined ? `(${this.state.quickFilterObj['Sent'].count})` : null}
        </button>
  )
}

我使用 Jest / 酶尝试了以下方法:

it("should HandlequickFilter with button click", () => { 
  wrapper.setProps({}); 
  wrapper.setState({quickFilterObj:"test"}); 
  wrapper.find('.quick-filter-div').at(0).simulate("click");
  expect(wrapper.state().quickFilterObj.New.checked).toEqual(true);
});

我怎样才能通过以下测试?

标签: reactjsunit-testingonclickjestjsenzyme

解决方案


必须在你的 jest.fn 函数中添加一个 return new Promise

//mocking functions
getSelectedLOAs  = jest.fn( () => {
return new Promise((resolve, reject) => {
resolve()
})
});


it("should test click event NEW  method", () => {
wrapper.setProps({
});
wrapper.find('COMPONENT').setState({ 
  quickFilterObj:{
    New: {
      checked: true
    },
    Sent: {
      checked: true
    },

   }, } );
wrapper.update();
wrapper.find('#New-testclick').simulate("click");
wrapper.find('#Sent-testclick').simulate("click");

推荐阅读