@domenico
To mock a global variable in Mocha, you can use the Sinon library, which provides functionalities for creating mocks, stubs, and spies. Here is an example of how you can mock a global variable in Mocha using Sinon:
1
|
npm install sinon --save-dev |
1 2 |
const sinon = require('sinon'); const globals = require('./globals.js'); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
describe('Test suite', function() { let globalVarMock; before(function() { globalVarMock = sinon.mock(globals, 'globalVar'); }); it('should test the global variable', function() { globalVarMock.returns('mocked value'); // your test code here }); after(function() { globalVarMock.restore(); }); }); |
In this example, sinon.mock()
is used to create a mock for the globalVar
property of the globals
module. You can then use the mock to set the return value for the global variable and write your test cases accordingly.
Remember to restore the mock using sinon.restore()
in the after
hook to clean up after the test.