How to test globals with mocha.js?

by elise_daugherty , in category: Javascript , 10 months ago

How to test globals with mocha.js?

Facebook Twitter LinkedIn Telegram Whatsapp

1 answer

by tressie.damore , 10 months ago

@elise_daugherty 

To test globals with Mocha.js, you can use the global object to access and test global variables. Here's an example:

  1. Create a test file (e.g., globals.test.js) and import Mocha, Chai, and the module you want to test.
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
const assert = require('chai').assert;

describe('Globals', function() {
  it('should have a global variable', function() {
    assert.isDefined(global.myGlobalVariable);
  });

  it('should have a global function', function() {
    assert.isFunction(global.myGlobalFunction);
  });
});


  1. Create a file where you define the global variables and functions (e.g., globals.js).
1
2
3
4
5
global.myGlobalVariable = 'Hello, world!';

global.myGlobalFunction = function() {
  return 'This is a global function.';
};


  1. Run the tests using Mocha in the terminal:
1
$ mocha globals.test.js


This will run the tests in the globals.test.js file and check whether the global variable and function are defined as expected.

Related Threads:

How to test promise catch with mocha.js?
How to programmatically skip a test in mocha.js?
How to test d3.js with mocha.js?
How to test jquery code with mocha.js?
How to test pure javascript module with mocha.js?
How to provide context of failed assertion in mocha.js?