【问题标题】:React.js unit test click event with Enzyme and SinonReact.js 单元测试点击事件与 Enzyme 和 Sinon
【发布时间】:2016-07-01 16:20:31
【问题描述】:

我正在尝试将间谍附加到我的反应组件上的单击事件。我正在使用Enzyme with MochaChai,但我无法通过以下测试:

it('Handles a Click Event', () => {
    let rootId = Bigtree['rootId'];
    const spy = sinon.spy();


    const render = shallow(<EnvH tree={smalltree.objects} 
    node={smalltree.objects[rootId]} root={rootId}/>);


    render.find('.toggler').simulate('click');

    expect(spy.called).to.be.true;
});

这是我正在测试的组件:

class EnvH extends React.Component {
return (
  <div className='top' key={Math.random()}>
    <div className={'tableRow row'} id={node.id} style={rowStyle} key={Math.random()}>
      <div style={nodeStyle} className={'root EnvHColumn ' + classNames(classObject)} key={Math.random()}>
        //Here is the actual Click Item in question
        <span className={'toggler'} onClick={this.toggleCollapseState.bind(this)}>{node.type} - {node.name}</span>
      </div>
      <ColumnContent columnType={'description'} nodeInfo={node.description} />
      <ColumnContent columnType={'createdOn'} nodeInfo={node.createdAt} />
      <ColumnContent columnType={'updatedOn'} nodeInfo={node.updatedAt} />
    </div>
    <div className={'Children'} style={childrenStyle} key={Math.random()}>
      {childNodes}
    </div>
  </div>
);

这是点击 span 时调用的函数:

  toggleCollapseState() {
     this.setState({collapsed: !this.state.collapsed});
  };

提前感谢您对此提供的任何帮助。我还应该提到,测试没有通过,说明它期望为真,但发现为假。

【问题讨论】:

  • 如果您需要更多信息,请告诉我。谢谢。

标签: reactjs onclick sinon enzyme


【解决方案1】:

您的测试没有通过,因为spy 函数没有提供给span.toggler 元素,所以它永远不会被它调用。 要使测试通过,您应该改为编写

sinon.spy(EnvH.prototype, 'toggleCollapseState')

然后

expect(EnvH.prototype.toggleCollapseState.calledOnce).to.be.true

【讨论】:

  • 哇感谢您的回复。我一直很忙,没有机会回来查看这个。我将在今天晚些时候尝试这个,如果它有效,则标记为正确。
猜你喜欢
  • 1970-01-01
  • 2019-08-31
  • 2020-10-10
  • 2017-02-26
  • 2021-02-22
  • 2018-12-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多