Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

159
Vistas
How to test non-export function in Reactjs

I have watched many tutorial videos on testing, but usually those tests test passed props to component or uses data-testid="". Is there a way to test non-exported functions? I read about rewire module which does this but problem with that is that Jest will not consider functions called from rewire in coverage reports.

// Random.js
import React from 'react'

export function sayHi() {
  return '👋';
}

function ListBox() {

  function saySecret() {
    return '🤫';
  }
    
  return (
    <div>ListBox</div>
  )
}

export default ListBox

First one which has export would be :

 // Random.test.js
 import { sayHi } from './Random.js';

 describe('sayHi', () => {
   it('returns wave emoji', () => {
     expect(sayHi()).toBe('👋');
   });
 });

How should I test saySecret?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

The short answer is you can't test those functions in isolation to the ListBox component itself.

The better answer is that you shouldn't. At least the react-testing-library philosophy is:

you want your tests to avoid including implementation details of your components

https://testing-library.com/docs/react-testing-library/intro/

.. and functions that exist only inside a component would very much count as implementation details.

If you need to increase your code coverage, then use react-testing-library to 'use' the component in such a way that the functions are called.

If the functions are reusable bits of code, then move them outside the component, and export them. Then you can test them in the usual way.

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda