Global variables in mocha

I’ve found it effective to set global variables on the global object in a beforeEach hook.

1
2
3
4
beforeEach(function() {
global.myVar: 'foo';
global.mySecondVar: 'bar';
});

If your variables are common across tests, you can stick that in a global file.

The beforeEach, I think, is almost always a better call than before. With before, the variables are established one time. After that, the state of those variables can be modified by methods in your codebase! You might notice this when tests pass in a single file, but not when the whole suite is run. beforeEach resets them for each test.

The use-case would be something like this:

1
2
3
it('should do the right thing', function(done) {
// use global.myVar
});
avatar

Dev Blog