Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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!

like image 554
sethpollack Avatar asked Feb 03 '12 19:02

sethpollack


People also ask

How do I export multiple functions from a single js file?

To export multiple functions in JavaScript, use the export statement and export the functions as an object. Alternatively, you can use the export statement in front of the function definitions. This exports the function in question automatically and you do not need to use the export statement separately.

How do I export a function in node JS?

The module.js is used to export any literal, function or object as a module. It is used to include JavaScript file into node. js applications. The module is similar to variable that is used to represent the current module and exports is an object that is exposed as a module.

How do I export a function from one node js file to another?

To include functions defined in another file in Node. js, we need to import the module. we will use the require keyword at the top of the file. The result of require is then stored in a variable which is used to invoke the functions using the dot notation.


1 Answers

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(); 
like image 140
benekastah Avatar answered Sep 20 '22 14:09

benekastah