get var from global beforeEach hook

1,036 views
Skip to first unread message

rajeshnar...@gmail.com

unread,
Mar 14, 2017, 1:55:26 PM3/14/17
to Mocha
Hey guys,

I need a help here. I am stuck, not sure what is wrong.

I am using mocha to write tests. I have global beforeEach(). I have variable declared. Is there a way to use this in testcase?? Here is an example

globalhook.js

describe('hooks', function() {
before();
console.log('reached before method');

beforeEach()
console.log('Reached beforeEach method');
var logger = 'test';



// teardown
afterEach();
console.log('reached afterEach method');

after();
console.log('reached after method');

});


My tests are in ./test folder. Filename is test1.js

describe('Array2', function() {
describe('#indexof2()', function() { 
it('should return -1 when the value is not present', function(done) {
assert.equal(-1, [1,2,3].indexOf(4));
done();
});
});
});


My question was to bring logger into my test without assigning to another global var. Probably from 'this.SOMETHING' would be great. Any help on this would be great. 

Vlad GURDIGA

unread,
Mar 15, 2017, 4:20:18 AM3/15/17
to Mocha
Hey Rajeshnar! 🙂

To have global before and beforeEach, they have to be outside any describe block, otherwise they are local to that describe block. Other than that, it looks like the this in the before blocks is not shared, only this in beforeEach blocks. 😶

Check it out:

    ~/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 ω  

Cheers! 🤓
Reply all
Reply to author
Forward
0 new messages