4

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?

1 Answer 1

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;
  }
Sign up to request clarification or add additional context in comments.

2 Comments

Ok, that make sense. the 'mock event object' confused me. So that can just be whatever object is passed to the event handler?
Can't for 10 min after post :/ will soon!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.