在React中测试附加在文档上的mousemove事件是否可能?

huangapple go评论63阅读模式
英文:

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

问题

我有一个附加到文档的mousemove事件。是否可以使用Enzyme、RTL或任何其他库进行测试?问题在于它不是一个React合成事件,因此在测试中不会触发...

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

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

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

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...

&lt;div onMouseDown={handleMouseDown}&gt;Element&lt;/div&gt;

const handleMouseDown = () =&gt; {
    document.addEventListener(&quot;mousemove&quot;, handleMouseMove);
};

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

答案1

得分: 1

以下是您要翻译的内容:

"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

);
wrapper.find('div').simulate('mousedown');
document.dispatchEvent(new MouseEvent('mousemove', { clientX: 50 }));
expect(handleMouseMove).toHaveBeenCalled();
});
});"

英文:

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 &#39;react&#39;;
import { mount } from &#39;enzyme&#39;;

describe(&#39;MouseEventExample&#39;, () =&gt; {
  it(&#39;should trigger mousemove event on document when onMouseDown is fired&#39;, () =&gt; {
    const handleMouseMove = jest.fn();
    const wrapper = mount(
      &lt;div onMouseDown={() =&gt; {
        document.addEventListener(&#39;mousemove&#39;, handleMouseMove);
      }}&gt;
        Element
      &lt;/div&gt;
    );
    wrapper.find(&#39;div&#39;).simulate(&#39;mousedown&#39;);
    document.dispatchEvent(new MouseEvent(&#39;mousemove&#39;, { clientX: 50 }));
    expect(handleMouseMove).toHaveBeenCalled();
  });
});