Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

152
Visualizações
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
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda