StandardNerd StandardNerd - 1 year ago 92
Javascript Question

How to export and import two different function objects in JavaScript?

I use Jasmine-Node to test Javascript code.

How can one export two different function objects like Confusions1 and Confusions2 so that both are available in the Jasmine-Node test file?

My attempt looks like this:

// confusions.js
var Confusions1 = function() {}; = function(num) {
// keep track of how many times `foo` is called

module.exports = Confusions1;

// second function object

var Confusions2 = function() {}; = function() {
var a = 2;;
}; = function() {
return this.a;

module.exports = Confusions2;

And my Jasmine Test file:

// confusions.spec.js

var Confusion = require('./confusions.js');

describe("chapter 1, common misconception ", function() {
describe("to assume `this` refers to the function itself: ", function() {
var confusion = new Confusion();

// some test code omitted


describe("to assume `this` refers to the function's scope", function() {
var confusion = new Confusion();

// test code omitted


I want it so that Confusions1 and Confusions2 from
are both usable in the two nested describe blocks within

I assume that I have to somehow initialize different objects after requiring the file
var Confusion = require('./confusions.js');

Something like
var confusion1 = new Confusions1(); var confusion2 = new Confusions2();
But how exactly (without splitting both Objects in two separate files)?

Answer Source

So you want to have a module that behaves like a container of exported values, in another words you want to export two functions:

// foo.js
var Confusion1 = function() {}
var Confusion2 = function() {}
exports.Confusion1 = Confusion1
exports.Confusion2 = Confusion2

Wherever you need this module, you could require this stuff like:

// bar.test.js
var confusions = require('path-to-the-foo-file')

Also as it seems you should check how module system that you are using works in general, check this answer: module.exports vs exports in Node.js

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download