Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

149
Views
React Hook key-up listener test (in Jest) not coming through

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?

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!