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 :

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();
  });
});

Leave a Reply