Mock node.js modules

Lets say I have this situation (architecture)

layer1 -> layer2 -> layer3

layers are just normal node.js modules (have some functions that are exported)

Layer1 requires layer2 and calls his functions and layer2 requires layer3 and calles his functions.

I want to test functions in layer1 but also mock layer3 (my function call in layer1 is propagated to layer3 and this one I want to mock).

What is the best way to do this? I have looked at this module : https://github.com/thlorenz/proxyquire but I don't think it supports mocking when things are going 2 or more level in depth like my example.

Thanks for any suggestions!

I've used mockery with great success, although it can get really tedious depending on what you want to mock.

However, your setup seems kinda wacky. If you want to unit test layer 1, you should only need to mock layer 2, and there shouldn't be any (direct) connection between layer 1 and layer 3.

Actually I was wrong with proxyquire. Yes, you can mock some module in 2 or more depth below your original module you are testing and it works fine as they showed in their example. Just put stub with path to that module which you are mocking. If you are mocking layer3, path of stub must be the same as the path to layer3 written in layer2 (so it is relative to layer2, not layer1 or some root).

We are doing integration testing and it sucks because we are using mongoDB database and there is no embedded database for mongo...there are some tries and alternatives but as I saw they are not good enough. So there was a root of my problems, we had to mock entire data layer. Before that we had real database on some machine and integration tests on CI server (Jenkins) were using that real database but that is not very good because you cannot run tests on your laptop for example.

So mocking entire data layer of application is also very bad solution but as I see there is no alternatives. If anyone had the same or similar situation feel free to write your solution here.

And also I would like complain about node.js modules in globally. Community is really active and large but lots of modules don't have backward compatibilities and even worse some of them doesn't interact with others very well. For example for HTTP client we used module restler and with new version of node we had to switch to restify because restler doesn't work very nice with new version of node. But also we used nock for mocking HTTP requests (really cool module btw) and BUMP - restify is not compatible with nock...maybe this is the price of this open source, community based technology and fast developing of node.js