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

I'm trying to simulate an onClick method in my unit tests using Enzyme for React. I've found

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;
  }

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745435176a4627575.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信