Reputation: 133
How to test a custom hook event with Enzyme and Jest? (useKeyPress)
My current custom hook: (get keyboard user event and update keyPress)
import React,{useEffect, useState} from 'react'
const useKeyPress = () => {
const [keyPress, setKeyPress] = useState('');
// If pressed key is our target key then set to true
const downHandler = (event) => {
setKeyPress(event.code);
}
const upHandler = () => {
setKeyPress('');
};
useEffect(() => {
window.addEventListener('keydown', downHandler);
window.addEventListener('keyup', upHandler);
return () => {
window.removeEventListener('keydown', downHandler);
window.removeEventListener('keyup', upHandler);
};
}, [])
return ([keyPress]);
}
export default useKeyPress;
Any Idea?
Upvotes: 1
Views: 1364
Reputation: 133
Thank's @Tom, I found a solution with the react testing library.
import useKeyPress from './../../src/component/useKeyPress/useKeyPress';
import { renderHook, act } from '@testing-library/react-hooks'
import {fireEvent} from '@testing-library/react'
test('Fire Enter keyboard event', () => {
const { result } = renderHook((() => useKeyPress()))
act(() => {
fireEvent.keyDown(window, { key: 'Enter', code: 'Enter' });
})
expect(result.current.keyPress).toBe('Enter');
});
Upvotes: 5