Simulate click on an element when using element.eventlistener in jest + enzyme set up

Viewed 388

I have a component lets say <MyComponent>. I have a <button>Click me</button> in the component which has a event listener on click added in useEffect

useEffect(() => {
    const btn = document.getElementById('button');
    if (btn) {
      btn.addEventListener('click', onButtonClicked, false);
    }
    return function cleanupListener() {
      if (btn) btn.removeEventListener('click', onButtonClicked);
    };
  }, []);

I need to simulate click on that button in test case using jest + enzyme. Went through one of the answer which had a solution like this but it didn't work

beforeEach(() => {
  const map = {};
  const namedByRefComponent = Wrapper.find("button");
  const namedByRefDomNode = namedByRefComponent.getDOMNode();
  const namedByRefDomNode = ReactDOM.findDOMNode(namedByRefComponent);
  namedByRefDomNode.addEventListener = jest
    .fn()
    .mockImplementation((event, cb) => {
      map[event] = cb;
    });
});

Can someone help me out with new solution or complete the above solution because I am not able to figure it out

Thanks in advance

0 Answers
Related