How to define a global variable outside the describe block in mocha?

by cali_green , in category: Javascript , 3 months ago

How to define a global variable outside the describe block in mocha?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

Member

by rollin , 3 months ago

@cali_green 

In Mocha, global variables can be defined in a separate file and imported into the test file using require. This allows the global variable to be accessed from any test case within the describe block.


Here is an example of how to define a global variable outside the describe block in Mocha:

  1. Create a separate file, let's call it globals.js, and define the global variable:
1
global.myGlobalVariable = 'Hello World';


  1. Save the file and import it into your test file:
1
2
3
4
5
6
7
8
const assert = require('assert');
require('./globals.js');

describe('Test Suite', () => {
  it('should access global variable', () => {
    assert.strictEqual(myGlobalVariable, 'Hello World');
  });
});


Now, the global variable myGlobalVariable can be accessed within any test case in the describe block without having to redefine it.