Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it possible to test mousemove events attached on document in React?

I have a mousemove event attached to document. Is it possible to test it with Enzyme or RTL or any other library? The problem is that it is not a react synthetic event, so it is not triggered in tests…

<div onMouseDown={handleMouseDown}>Element</div>

const handleMouseDown = () => {
    document.addEventListener("mousemove", handleMouseMove);
};

const handleMouseMove = ({ clientX }) => {
    console.log(clientX)
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

it’s not possible since they are designed to work with React synthetic events only.

you can still test the behavior of your mousemove event by simulating the mouse movement using the fireEvent method from RTL or simulate method from Enzyme.

   import React from 'react';
import { mount } from 'enzyme';

describe('MouseEventExample', () => {
  it('should trigger mousemove event on document when onMouseDown is fired', () => {
    const handleMouseMove = jest.fn();
    const wrapper = mount(
      <div onMouseDown={() => {
        document.addEventListener('mousemove', handleMouseMove);
      }}>
        Element
      </div>
    );
    wrapper.find('div').simulate('mousedown');
    document.dispatchEvent(new MouseEvent('mousemove', { clientX: 50 }));
    expect(handleMouseMove).toHaveBeenCalled();
  });
});
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading