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 badges1 Answer
Reset to default 5according 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;
}