'Jest: simulate key press not working in React hook
I have a simple hook firing provided function on key up:
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])
}
I want to test it using Enzyme:
import { shallow } from 'enzyme'
import React from 'react'
import useKeyUp from 'utils/hooks/useKeyUp'
const TestComponent = ({key, callback}) => {
useKeyUp(key, callback)
return (
<div>
test
</div>
)
}
test('executes handler on Enter key up', () => {
const callback = jest.fn()
const testComponent = shallow(
<TestComponent
key={'Enter'}
callback={callback}
/>)
testComponent.simulate('keypress', { charCode: 13 })
expect(callback).toHaveBeenCalledTimes(1)
But callback function has not been called. I know the hook is working because I tested it manually. How can I properly simulate the event?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
