node.js:以任何方式逐个导出文件中的所有函数(例如,启用单元测试)

set*_*ack 23 unit-testing module node.js

在node.js中,是否有任何快捷方式可以导出给定文件中的所有函数?我想为单元测试目的这样做,因为我的单元测试与我的生产代码分开.

我知道我可以通过手动导出每个函数,如下所示:

exports.myFunction = myFunction;
Run Code Online (Sandbox Code Playgroud)

但我想知道是否有更简单/更光滑的方式来做到这一点.

(是的,我意识到出于模块化的原因,导出所有功能并不总是一个好主意,但出于单元测试的目的,你确实希望看到所有的小功能,这样你就可以逐个测试它们.)

谢谢!

ben*_*tah 17

你可以这样做:

// 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();
Run Code Online (Sandbox Code Playgroud)

或这个:

// 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();
Run Code Online (Sandbox Code Playgroud)

或这个:

// 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();
Run Code Online (Sandbox Code Playgroud)

  • 谢谢 - 但这仍然意味着按名称明确列出每个功能.所以我猜没有"出口*"类型的概念? (3认同)