How to declare a global array in node.js mocha?

by wilmer.lemke , in category: Javascript , 3 months ago

How to declare a global array in node.js mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by elise_daugherty , 3 months ago

@wilmer.lemke 

To declare a global array in Node.js Mocha, you can simply define the array outside of any function or block scope in your test file. Here is an example:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
// Initialize a global array
global.myArray = [];

describe('My test suite', function() {
    it('should be able to access the global array', function() {
        // Add elements to the global array
        global.myArray.push('element1', 'element2');
        
        // Access the global array
        console.log(global.myArray); // Output: ['element1', 'element2']
    });
});


In this example, we declare a global array myArray by setting it on the global object. This allows us to access and manipulate the array in any test within the test suite.