Search code examples
javascriptunit-testingjasmine-node

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() {};

Confusions1.prototype.foo = function(num) {
        // keep track of how many times `foo` is called
        this.count++;
}

module.exports = Confusions1;

// second function object

var Confusions2 = function() {};

Confusions2.prototype.foo = function() {
        var a = 2;
        this.bar(); 
};

Confusions2.prototype.bar = 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 confusions.js are both usable in the two nested describe blocks within confusions.spec.js

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)?


Solution

  • 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')
    console.log(confusions.Confusion1)
    console.log(confusions.Confusion2)
    

    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