使用React中的Enzyme模拟带有参数的onClick方法

时间:2017-07-06 22:48:01

标签: javascript reactjs enzyme

我尝试使用Enzyme for React在我的单元测试中模拟onClick方法。我找到了许多模拟onClick的指南,这些指南需要一些事件e,例如:

handleClick(e) {
    // Does something
}

....
<MyComponent
onClick = {handleClick}
></MyComponent>

但是我希望能够模拟我的onClick,它不会将事件作为参数,而是采取其他方式,即:

onClick = {() => handleClick(myParam)}

我已尝试使用.simulate('click', [myParam]);,但未按预期传递参数。

我如何模拟将特定参数发送给处理程序的点击?

1 个答案:

答案 0 :(得分:2)

根据文件说明:

  

.simulate(event [,mock])=&gt;自我模拟事件

     

参数

     

event(String):要模拟的事件名称mock(对象   [可选]):将与之合并的模拟事件对象   事件对象传递给处理程序。

因此您需要修复代码并传递对象:

<div class="card-title">
  <div class="title-actions">

    <a href="#" id="id_select_request_document" title="Select file(s)" class="btn btn-icon select-button" data-turbolinks="false" data-save-label="Ok" data-close-label="Cancel" data-copy-to="9" data-reload="true" data-url="/documents/select/8/">
      <i class="material-icons">folder</i>
    </a>

    <a href="#" id="id_upload_request_document" title="Upload file(s)" class="btn btn-icon upload-button" data-turbolinks="false" data-url="/documents/upload/9/" data-complete-post="/requests/validate-requirements/2/" data-max-uploader-connections="1" style="position: relative; overflow: visible; direction: ltr;">
      <i class="material-icons">cloud_upload</i>
      <i style="overflow: hidden;display: block;position: absolute;top: 0;left: 0;width: 35px;height: 35px;"><input
                        multiple="multiple" type="file" name="file"
                        style="position: absolute; right: 0px; top: 0px; font-family: Arial; font-size: 118px; margin: 0px; padding: 0px; cursor: pointer; opacity: 0;"></i>
    </a>
    <div class="wrapper">
      <div id="overlay"></div>
      <a href="#" title="Send email - rejected file(s)" class="btn btn-icon select-another-button" data-url="/messaging/send/2/">
        <i class="material-icons">assignment_late</i>
        <div class="alert alert-success" id="send-message" style="display: none;">
          <p>
            The message was sent to the client. Please wait 5 minutes <br> before sending the message again.
          </p>
        </div>
      </a>
    </div>

    <a href="/admin/filer/folder/9/list/" class="btn-icon"><i class="material-icons">settings</i></a>

  </div>
  <h5>Request documents</h5>
</div>

您还可以查看实现,看看如何将其传递给事件处理程序here

.simulate('click', {myParam});