Home > Blockchain >  How can I test a pure function does not exports from the other source with jest
How can I test a pure function does not exports from the other source with jest

Time:03-04

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

CodePudding user response:

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.

Another technique (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.

At the end of the day you can't really test private 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.

  • Related