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

285
Visualizações
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?

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