I have a pop up and I would like to test that when I press ESC on my keyboard that the pop up closes. The functionality works however I want to get my test to pass. I don't know how to simulate a keyDown press on the whole document and not just the Modal pop up component.
Here it my test right now:
test("it should call the onKeyDown handler on key ESC press", () => {
const onKeydownSpy = jest.fn();
const component = mount(
<div id="wrapper">
<Modal
isOpen={false}
portalParent="#wrapper"
onClose={() => {}}
id="123"
>
<p>Modal</p>
</Modal>
</div>
);
component.simulate("keydown", { keyCode: 27 });
expect(onKeydownSpy).toHaveBeenCalledTimes(1);
expect(onKeydownSpy).toHaveBeenCalledWith(0);
});
Here is my code:
const handleKeyDownEvent = useCallback(event => {
if (event.keyCode === 27) {
onClose();
}
}, []);
useEffect(() => {
if (isOpen) {
document.addEventListener("keydown", handleKeyDownEvent);
} else {
document.removeEventListener("keydown", handleKeyDownEvent);
}
}, [handleKeyDownEvent, isOpen]);
Thanks in advance, let me know if you need more information
Aucun commentaire:
Enregistrer un commentaire