I do not have much experience with Jest and am stuck in writing test for this Hook component:
export default function useKeyUp(key: Key, onKeyUp: Function) {
useEffect(() => {
const handleUp = (event: KeyboardEvent) => {
const { key: releasedKey } = event
if (key === releasedKey) {
if (onKeyUp) {
onKeyUp()
}
}
}
window.addEventListener('keyup', handleUp)
return () => {
window.removeEventListener('keyup', handleUp)
}
}, [key, onKeyUp])
}
This is how I set the test:
const TestComponent = ({key, callback}) => {
useKeyUp(key, callback)
return (
<div>
test
</div>
)
}
test('executes handler on Enter keydown and unsubscribes after unmount', () => {
const callback = jest.fn()
const testComponent = mount(
<TestComponent
key={'Enter'}
callback={callback}
/>)
document.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }))
expect(callback).toHaveBeenCalledTimes(1)
document.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }))
expect(callback).toHaveBeenCalledTimes(1)
testComponent.unmount()
document.dispatchEvent(new KeyboardEvent('keyup', { key: 'Enter' }))
expect(callback).toHaveBeenCalledTimes(1)
})
It fails in step one, the function is ran 0 times by that time. Debugging it I see that the key is undefined - but why, when I am sending it as props to the component and callback goes through alright?