How to unit test a Node.js module that requires other modules and how to mock the global require function?

You can now!

I published proxyquire which will take care of overriding the global require inside your module while you are testing it.

This means you need no changes to your code in order to inject mocks for required modules.

Proxyquire has a very simple api which allows resolving the module you are trying to test and pass along mocks/stubs for its required modules in one simple step.

@Raynos is right that traditionally you had to resort to not very ideal solutions in order to achieve that or do bottom-up development instead

Which is the main reason why I created proxyquire – to allow top-down test driven development without any hassle.

Have a look at the documentation and the examples in order to gauge if it will fit your needs.

Leave a Comment