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

148
Visualizações
How to pass function to a custom hook while writing unit test in Jest/React

I have to write a unit test of a custom hook used in index.js (see this implementation) in which I am passing a function as a parameter. I don't know how to pass a function to a hook in unit test. I am a beginner.

How can I achieve a 100% coverage for my unit test?

useBrowserFwdBackButton.ts (file in which custom hook is available)

import React from 'react';
    
    const useBrowserFwdBackButton = (fn: any) => {
      const cb = React.useRef(fn); // init with fn, so that type checkers won't assume that current might be undefined
    
      React.useEffect(() => {
        cb.current = fn;
      }, [fn]);
    
      React.useEffect(() => {
        const onForwardBackButtonEvent = (...args: any[]) => cb.current?.(...args);
    
        window.addEventListener('popstate', onForwardBackButtonEvent);
    
        return () => window.removeEventListener('popstate', onForwardBackButtonEvent);
      }, []);
    };
    
    export default useBrowserFwdBackButton;

index.js (from where hook is calling from functional component)

useBrowserFwdBackButton((e) => {
    e.preventDefault();
    if (attachmentListLength !== 0) {
      dispatch(deleteGoogleDocument(attachmentList));
    }
  });
about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

Assuming you are using jest and @testing-library/react-hooks for hook testing

you can creat mock function with jest.fn() eg.

const mockFunction = jest.fn();
const { result } = renderHook(() => useBrowserFwdBackButton(mockFunction));
const { .... } = result.current;

// since it's attached to windows event, you need to trigger the "popstate" event

// expects here
expect(mockFunction).toBeCalledTimes(1);

additional info (trigger window event) How to trigger a window event during unit testing using vue-test-utils

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