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

simulating an onClick method with a parameter using Enzyme in React

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

handleClick(e) {
    // Does something
}

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

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

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

我试过使用 .simulate('click', [myParam]); 但它没有像我预期的那样传递参数。

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

根据文档,它指出:

.simulate(event[, mock]) => Self Simulate events

Arguments

event (String): The event name to be simulated mock (Object [optional]): A mock event object that will be merged with the event object passed to the handlers.

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

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

您还可以查看实现并了解它是如何传递给事件处理程序的 here:

simulate(event, ...args) {
    const handler = this.prop(propFromEvent(event));
    if (handler) {
      withSetStateAllowed(() => {
        // TODO(lmr): create/use synthetic events
        // TODO(lmr): emulate React's event propagation
        performBatchedUpdates(this, () => {
          handler(...args);
        });
        this.root.update();
      });
    }
    return this;
  }