英文:
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...
<div onMouseDown={handleMouseDown}>Element</div>
const handleMouseDown = () => {
document.addEventListener("mousemove", handleMouseMove);
};
const handleMouseMove = ({ clientX }) => {
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 '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();
});
});
评论