// 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?
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.