I want write a test using Jest and Enzyme that tests a component that has an event listener, such that when a mousedown event occurs outside of a given html element, a change occurs (in this example, a state value is toggled). I am using jest to mock the event listener and simulate the mousedown event, however, when I try to run this test, I am getting the following error message:
TypeError: Failed to execute 'contains' on 'Node': parameter 1 is not of type 'Node'.
Obviously I think that <div />
is not the right value I should be providing when I simulate my mousedown event with map.mousedown({ target: <section /> });
. How do I properly simulate a mousedown event that occurs outside of my component? You can see the code below. Thanks!
sampleComponent.jsx:
import * as React from 'react';
const SampleComponent = () => {
const [state, setState] = React.useState(false);
const ref = React.useRef(null);
const handleClickOutside = (event) => {
if (
!ref.current.contains(event.target)
) {
setState(true);
}
};
React.useEffect(() => {
document.addEventListener('mousedown', handleClickOutside);
return () => document.removeEventListener('mousedown', handleClickOutside);
});
return (
<div
id="sample-div"
ref={ref}
>
{`State value is: ${state}`}
</div>
);
};
export default SampleComponent;
sampleComponent.test.jsx:
import * as React from 'react';
import { mount } from 'enzyme';
import SampleComponent from './sampleComponent';
const setup = () => mount(<SampleComponent />);
test('testing mousedown', () => {
const map = {};
document.addEventListener = jest.fn((event, callback) => {
map[event] = callback;
});
const wrapper = setup();
expect(wrapper.find('#sample-div').text()).toBe('State value is: false');
map.mousedown({ target: <section /> });
expect(wrapper.find('#sample-div').text()).toBe('State value is: true');
});