-
Notifications
You must be signed in to change notification settings - Fork 51
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: a custom hook to listen to key presses (#391)
* feat: a custom hook to listen to key presses * chore: changed useKeyPress to a more aproprietade folder * feat: add tests for useKeyPress * refactor: reducing redundancies in code
- Loading branch information
1 parent
575ca50
commit bd3bc1f
Showing
2 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,35 @@ | ||
import { act, renderHook } from '@testing-library/react'; | ||
|
||
import useKeyPress from './useKeyPress'; | ||
|
||
describe('useKeyPress', () => { | ||
let action: (event: KeyboardEvent) => void; | ||
let targetKey: string; | ||
|
||
beforeEach(() => { | ||
action = vi.fn(); | ||
targetKey = 'Enter'; | ||
}); | ||
|
||
it('calls action function when target key is pressed', () => { | ||
renderHook(() => useKeyPress(targetKey, action)); | ||
|
||
act(() => { | ||
const event = new KeyboardEvent('keydown', { key: targetKey }); | ||
window.dispatchEvent(event); | ||
}); | ||
|
||
expect(action).toHaveBeenCalled(); | ||
}); | ||
|
||
it('does not call action function when a different key is pressed', () => { | ||
renderHook(() => useKeyPress(targetKey, action)); | ||
|
||
act(() => { | ||
const event = new KeyboardEvent('keydown', { key: 'Escape' }); | ||
window.dispatchEvent(event); | ||
}); | ||
|
||
expect(action).not.toHaveBeenCalled(); | ||
}); | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,19 @@ | ||
import { useEffect } from 'react'; | ||
|
||
function useKeyPress( | ||
targetKey: string, | ||
action: (event: KeyboardEvent) => void | ||
): void { | ||
const downHandler = (event: KeyboardEvent) => { | ||
if (event.key === targetKey) action(event); | ||
}; | ||
|
||
useEffect(() => { | ||
window.addEventListener('keydown', downHandler); | ||
return () => { | ||
window.removeEventListener('keydown', downHandler); | ||
}; | ||
}, []); | ||
} | ||
|
||
export default useKeyPress; |