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

229
Visualizações
How to test react component with onClick function Jest/React testing library

I am trying to get to 100% coverage for my tests in one of them it highlights the onClick function which sets the state for a component: this is the component:

I have a button which has an onClick function as below, the button is mapped in from an array of objects.

  const [activeIdx, setActiveIdx] = React.useState(0);

  <button type="button" data-testid={'btn-test} 
     onClick={() => {setActiveIdx(() => index); inner.cb(index)}}key={inner.id}>
     {inner.title}</button>

This button clicks and sets the active index of the button clicked as this is a button group. How would I test the onClick function in jest/react-testing library?

I have some tests that check a few things like:

    it('Should render without crashing', (): void => {
        const div = document.createElement("div");
        ReactDOM.render(<ButtonGroup data={Data}/>, div);
        ReactDOM.unmountComponentAtNode(div);
    });

    const btn = screen.getByRole('button', {name: '1 hour'});

    it('Should be clicked', (): void => {
       fireEvent.click(btn);
       expect(btn).toBeValid();
    });

But how to mock the function and check that?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

This actually goes against the core idea of testing library where

Testing Library encourages you to avoid testing implementation details like the internals of a component

There are two solutions you can try:

  1. Create a visual response based off the state change, then check for that visual response
  2. Export a function that you use in onClick then within the test you can mock that function to see if it was called, what was returned, etc.
about 4 years ago · Juan Pablo Isaza Relatório

0

You can simulate a click with Enzyme, here is a blog about it https://preactjs.com/guide/v10/unit-testing-with-enzyme/.

wrapper.find('btn').simulate('click');
about 4 years ago · Juan Pablo Isaza Relatório
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