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

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

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 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!