Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

287
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!