Stubbing a Standalone Function in Javascript
Photo by Lubo Minar / Unsplash
Why
Some libraries like Ora have set their module.exports
to a function.
Testing libraries like Sinon rely on having an object to stub on, for example:
const stub = sinon.stub(obj, 'method');
If there is no object you can't stub the function, which makes libraries like Ora 'unstubable' out of the box. There is a certain frustration about it with no clear solution.
How
One possible solution for the problem is to create a proxy module with cache to allow stubbing.
Import it in your code const lib = patch('lib');
and use cache
object in your tests.
The obvious downside is that you have to import your libs like const lib = patch('lib');
Would love to find a better approach. If know one please let me know.