My Online Food Delivery App and why I gave up on it.

A few weeks ago I had an idea of developing a food delivery app business. While it never went as planned and I had to give-up on the idea all together, the whole experience was totally worth it. Here…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




Optionally exporting modules for testing in NodeJS

Click here for the TL;DR

There are a few solutions to this problem, for example:

(1) is usually enough. (2) is a suitable solution, however things get complicated if you want to manage (and stub/spy on) dependencies of the module. (3) is potentially writing code for the sake of tesing, but in our particular case it actually reduced the amount of complicated stubbing of the module’s dependencies. Also, it’s fun to do so let’s see how.

A Node application entry point might look something like this…

Which doesn’t seem all that bad. But if you wanted to stub/spy/mock the instance of SomeDependency passed to the constructor, you’d have to do something like this…

On a typical project with good test coverage you might expect to see a test-to-source code ratio of 2 or 3:1, which means you’re giving yourself (and your fellow engineers) a lot of unnecessary additional boilerplate to write.

To determine if the current module is being run as the root Node process, you just need to do this:

const isNodeProcess = require.main === module

So, to optionally export the module or execute it, you just need to do something like…

Your test case now looks a lot less complicated (and more likely a regular unit test)…

require.main === module when a module is the entry point of a Node process. If you would rather export something when the file is loaded via a require statement, simply do so when that statement is false.

Add a comment

Related posts:

The First Day of the Rest of My Life as a Widower

After more than 40 years of marriage, my wife died suddenly and unexpectedly. The mysteriousness of her death suspended time.

Meet the people behind OneLedger

Every start-up just like every company began with a flick of a switch idea. The idea then quickly grows from just a small flame to a raging unstoppable fire with a burning need to exist. To live…

Wurst Idea Ever?

Have you ever felt like visiting Turkey, but got scared, irritated or were smart enough to play it safe and thus backed down from this idea? Well good news. If you were looking forward to get to know…