~/tmp/how-mocha-context-works ω mocha --version
3.2.0
~/tmp/how-mocha-context-works ω tree test/
test/
├── global.js
└── one.js
0 directories, 2 files
~/tmp/how-mocha-context-works ω cat test/global.js
before(() => {
this.globalGlobal = '42 global';
console.log("global before");
});
beforeEach(function() {
this.eachGlobal = '42';
console.log('global before each');
});
~/tmp/how-mocha-context-works ω cat test/one.js
describe('the test name', function() {
before(function() {
console.log('local before, doesn’t work', this.globalGlobal);
});
beforeEach(function() {
console.log('local beforeEach has access to the global beforeEach context', this.eachGlobal);
});
it('works as expected', function() {
console.log('test can access beforeEach context', this.eachGlobal);
console.log('test can NOT access before context', this.globalGlobal);
});
});
~/tmp/how-mocha-context-works ω mocha
global before
the test name
local before, doesn’t work undefined
global before each
local beforeEach has access to the global beforeEach context 42
test can access beforeEach context 42
test can NOT access before context undefined
✓ works as expected
1 passing (6ms)
~/tmp/how-mocha-context-works ω