I\'m trying to simulate a .click()
event
on a React element but I can\'t figure out why it is not working (It\'s not reacting when I\'m firing the
React tracks the mousedown
and mouseup
events for detecting mouse clicks, instead of the click
event like most everything else. So instead of calling the click
method directly or dispatching the click
event, you have to dispatch the down and up events. For good measure I'm also sending the click
event but I think that's unnecessary for React:
const mouseClickEvents = ['mousedown', 'click', 'mouseup'];
function simulateMouseClick(element){
mouseClickEvents.forEach(mouseEventType =>
element.dispatchEvent(
new MouseEvent(mouseEventType, {
view: window,
bubbles: true,
cancelable: true,
buttons: 1
})
)
);
}
var element = document.querySelector('div[class="UFIInputContainer"]');
simulateMouseClick(element);
This answer was inspired by Selenium Webdriver code.