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

278
Visualizações
In Jest, how to test a function declared inside a function?

I am trying to test a function that is declared inside another function(Parent). I tried a few things but was not able to test that. I am using react library and JEST testing framework in the project.

Here is the service file (service.ts) function which I am trying to test:

import { useThisHook } from './base-hooks';

export function someFunction(param: string) {

  const [
    resolveFunction,
    ,
    { loading, error },
  ] = useThisHook();
  
  const childFun = (param : number) => {
     resolveFunction(someArguments);
  }
  
  return{
     someValue: childFun
  }
}

Here is the spec file code:

import * as SomeHooks from './base-hooks';
import * as Service from './service';

describe('Service function', () => {
  beforeEach(() => {
     jest.spyOn(SomeHooks, 'useThisHook').mockReturnValue(
      {
         //Some Value
      }
     );
  });

  test('Some function test', () => {
    const someFunctionResponse = Service.someFunction('string');

    expect(someFunctionResponse).toEqual({
        someValue: expect.any(Function),
    });
  });
});

Till here it is fine. Tests are also getting passed but the problem is that childFn is not getting the coverage and that's what my requirement is. I am new to React and Jest. I am not able to understand how can I achieve that. I tried many things but didn't succeed.

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Your childFn is not being called, that's why it's not getting coverage.

You could either refactor the whole childFn to a new hook and test it individually with something like react-hooks-testing-library.

Or you could separate the childFn and declarate it outside the someFunction scope pass the resolveFunction and then test it.

You only get coverage if the code is actually called, not when it is declared.

about 4 years ago · Santiago Trujillo 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