Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

node.js: any way to export ALL functions in a file en masse (e.g., to enable unit testing), vs. one by one

node.js: any way to export ALL functions in a file en masse (e.g., to enable unit testing), vs. one by one

Problem

in node.js, is there any shortcut to export ALL functions in a given file? i want to do this for unit testing purposes, as my unit tests are in a separate file from my production code.

I know i can go through and export each function manually, as in:

exports.myFunction = myFunction;

But i'm wondering if there is a simpler/slicker way to do this.

(and yes, i realize for modularity reasons it isn't always a good idea to export all functions, but for unit testing purposes you do want to see all the little functions so you can test them piece by piece.)

Thanks!

Problem courtesy of: sethpollack

Solution

You could do something like this:

// save this into a variable, so it can be used reliably in other contexts
var self = this;

// the scope of the file is the `exports` object, so `this === self === exports`
self.fnName = function () { ... }

// call it the same way
self.fnName();

Or this:

// You can declare your exported functions here
var file = module.exports = {
  fn1: function () {
    // do stuff...
  },
  fn2: function () {
    // do stuff...
  }
}

// and use them like this in the file as well
file.fn1();

Or this:

// each function is declared like this. Have to watch for typeos, as we're typing fnName twice
fnName = exports.fnName = function () { ... }

// now you can use them as file-scoped functions, rather than as properties of an object
fnName();
Solution courtesy of: benekastah

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

node.js: any way to export ALL functions in a file en masse (e.g., to enable unit testing), vs. one by one

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×