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

104
Visualizações
React / Jest testing history.push correctly for 100% code coverage

I have a function in my app as follows:

import React from 'react';
import { useHistory } from "react-router-dom";

const Main: React.FunctionComponent<{ data: any[] }> = ({
    data: result }) => {

    const history = useHistory();

    return (
        <>  
            {result?.map(inner => {

                const handleClick = () => {
                    history.push(`/list/${result?.id}`, { item: result?.item})
                }

                return (
                    <div key={result.id} onClick={handleClick}>
                        <div className="inner-content">{result?.content}</div>
                    </div>
                )
            })}
        </>
    )
}

export default Main;

I have a test case in my tests as follows:

const mockHandleClick = jest.fn();

jest.mock('react-router-dom', () => ({
    ...jest.requireActual('react-router-dom'),
    useHistory: () => ({
        push: mockHandleClick,
    }),
}));

it('Should test history push', () => {
    let tree = create(<div onClick={mockHandleClick}><div class="inner- 
    content">Content Here</div></div>);
    const button = tree.root.findByType('div')
    button.props.onClick()
    expect(mockHandleClick).toHaveBeenCalledTimes(1);
});

This passes, but the handleClick function still flags up in the code coverage? so I am not achieving 100% coverage.

Any Idea's?

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

0

I think you're having trouble hitting more complete code coverage because you are declaring a handleClick callback for each iterated result element object. The test appears to only select the first div.

Refactor the handleClick handler into the component body and pass a single handler to each mapped item and pass the mapped object to the handler.

const Main: React.FunctionComponent<{ data: any[] }> = ({
  data: result }) => {

  const history = useHistory();

  const handleClick = (inner) => () => {
    history.push(`/list/${inner?.id}`, { item: inner?.item });
  };

  return (
    <>
      {result?.map(inner => (
        <div key={inner.id} onClick={handleClick(inner)}>
          <div className="inner-content">{inner?.content}</div>
        </div>
      ))}
    </>
  );
};
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