最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - simulating an onClick method with a parameter using Enzyme in React - Stack Overflow

programmeradmin2浏览0评论

I'm trying to simulate an onClick method in my unit tests using Enzyme for React. I've found many guides to simulating an onClick that takes some event e, such as:

handleClick(e) {
    // Does something
}

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

However I want to be able to simulate my onClick which does not take the event as a parameter but takes something else instead, ie:

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

I've tried using .simulate('click', [myParam]); but it did not pass the parameter as I expected.

How would I go about simulating a click that sends a specific parameter to the handler?

I'm trying to simulate an onClick method in my unit tests using Enzyme for React. I've found many guides to simulating an onClick that takes some event e, such as:

handleClick(e) {
    // Does something
}

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

However I want to be able to simulate my onClick which does not take the event as a parameter but takes something else instead, ie:

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

I've tried using .simulate('click', [myParam]); but it did not pass the parameter as I expected.

How would I go about simulating a click that sends a specific parameter to the handler?

Share Improve this question asked Jul 6, 2017 at 22:48 Tevon Strand-BrownTevon Strand-Brown 1,7483 gold badges20 silver badges30 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 5

according to the documentaton it states that:

.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.

so you need to fix your code and pass an object:

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

You can also take a look at the implementaion and see how it is passed to the event handler 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;
  }
发布评论

评论列表(0)

  1. 暂无评论