Ruslan Plastun
Ruslan Plastun

Reputation: 2254

Test module's global variables in Mocha

I have a module that I want to test:

var array = []; //<--- mobule local array

var Deleter = {
    DeleteNumb: function(number) {
        console.log("TEST", array); //<--- Console
        var index = array.indexOf(number);

        if(index != -1) {
            array.splice(index, 1);
        }
    }
};

module.exports = Deleter;

And I have a test file throught which I am trying to test this file:

var expect = require("chai").expect;
var Deleter = require("../DELETE.js");

describe("Testing Deleter", function() {
    it("DeleteNumb", function() {
        var array = [1,2,3,4,5]; // <--- test arrray

        Deleter.DeleteNumb(3);

        expect(array).to.be.length(4);
    });
});

I want to test if an array variable is indeed spliced if I call DeleteNumb function. But in the console I get: "TEST: [ ]", because array variable that is local to the module being tested is indeed empty. My question is how to modify that local array for my testing? I do not want to parse the array as an argument for DeleteNumb. Thanks in advance.

Upvotes: 1

Views: 1249

Answers (1)

Ruslan Plastun
Ruslan Plastun

Reputation: 2254

All I needed to do was to add my DELETE.js local array to exports like that:

module.exports.array = array;
module.exports.Deleter = Deleter;

And then in the test file I could modify that local array as I wanted:

var expect = require("chai").expect;
var Deleter = require("../DELETE.js").Deleter;
var testarray = require("../DELETE.js").array;

describe("Testing Deleter", function() {
    it("DeleteNumb", function() {
        testarray.push(1,2,3,4,5);//modifying DELETE.js array using module.exports reference

        Deleter.DeleteNumb(3);

        expect(testarray).to.be.length(4);
    });
});

Upvotes: 1

Related Questions