简体   繁体   中英

Scoping mecanism with nodejs and require

Trying to perform unit test of client-side javascript using nodejs and jasmine-node. I was able to create the window and document variables, a $ variable, setup the environment (with npm, don't forget to define NODE_PATH!). But now I am stuck on this.

The functions I want to test are within a module. I can import (require) the module but the variable in which the module is imported in is not accessible from nodejs (or the jasmine spec file for the same reason I imagine).

Here is the module:

var test_module = (function () {
  var init = function () {
    return "toto";
  }

  return { init: init };
})();

In the variable test_module, we should find the variable containing the dictionary with all the exported function (here only one called init).

In nodejs:

> require('test.js');
{}
> test_module
ReferenceError: test_module is not defined
    at repl:1:2
    at REPLServer.self.eval (repl.js:110:21)
    at Interface.<anonymous> (repl.js:239:12)
    at Interface.EventEmitter.emit (events.js:95:17)
    at Interface._onLine (readline.js:202:10)
    at Interface._line (readline.js:531:8)
    at Interface._ttyWrite (readline.js:760:14)
    at ReadStream.onkeypress (readline.js:99:10)
    at ReadStream.EventEmitter.emit (events.js:98:17)
    at emitKey (readline.js:1095:12)

I am not sure to understand how the scoping works in nodejs. I tried to put:

global.test_module = (function () {

and this works but this is not what I want to do. My javascript is supposed to run in the browser once tested, and global won't do...

Side note: Unit testing of client-side javascript using a command line, browserless and serveress solution would deserve a god tutorial I guess. There are some out there but they are usually incomplete.

Ok, thanks to htatche's answer, I found a workaround (it seems that client-side javascript unit testing is the land of workaround...):

var test_module = (function () {
  var init = function () {
    return "toto";
  }

  return { init: init };
})();

if(typeof exports != 'undefined'){
    module.exports = test_module;
}

Explained here: http://caolanmcmahon.com/posts/writing_for_node_and_the_browser/
This way I keep nodejs and the browser happy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM