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

169
Views
How can I test a pure function does not exports from the other source with jest
 // add.js
 const add = (a, b) => a +b;

How can I test the add function? I want to test add function logic. But I don't know how to test it. Because the function is not exported. I want this function to be called only on add.js.

Do I have to export this add function for testing with jest?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

There's a lot of debate on this topic. If your add function is not exported, it is considered "private/internal" to your module and is not part of the public API. Many people argue that you should only test your public API, others argue that you will need to export your private functions if you wish to test them. Both sides make great points and it boils down to a matter of preference.

My preferred technique is to put these types of helper functions in a separate module which is tested separately and imported wherever you need it. These methods become "public", but in practice I have found that it doesn't hurt anything and you might actually end up reusing the code somewhere else without needing to refactor anything.

You can also try exporting your methods but mark them as @private using the popular JSDoc syntax. This is merely a hint to developers that they shouldn't import or use the method, and some editors/IDEs might even hide the method from intellisense.

/** @private */
export const add = (a, b) => a + b;

At the end of the day you can't really test private (non-exported) methods without using some tool like rewire. I used to use rewire a lot, however, I don't recommend it any more as it makes your tests more complex and brittle. I have found that good tests are simple and easy to read, which is not the case when you use things like rewire. Don't get caught in the trap of "developers shouldn't be able to see or use this private function" - it's a toxic way to think about your code IMO.

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!