Mocha and this context
So, I have this code:
describe('main describe', function() {
afterEach(function() {
//this.prop === undefined
});
describe('sub', function() {
it('should do something', function() {
this.prop = 'test';
});
});
});
I do not know why this.prop
in main
afterEach
there undefined
, because the next code works as expected:
describe('main describe', function() {
afterEach(function() {
//this.prop === 'test'
});
it('should do something', function() {
this.prop = 'test';
});
});
Why is the first code not working even though I would like this.prop to be equal 'test'
instead of undefined
?
Is a keyword this
only bound to the function describe
it contains directly?
source to share
Yes, everyone describe
gets a new object Context
. (All the classes I mention can be found in the Mocha source code.) You can get what you are trying to do:
describe('main describe', function() {
afterEach(function() {
console.log(this.prop);
});
describe('sub', function() {
it('should do something', function() {
this.test.parent.ctx.prop = 'test';
});
});
});
The line this.test.parent.ctx.prop
is the key. this
is a Context
challenge-related one it
. this.test
is the object Test
associated with the call it
. this.test.parent
is the object Suite
associated with the call describe
that immediately contains the call it
. this.test.parent.ctx
is the context in which the call appears describe
, which in the same context as this
, in the call afterEach
is the same context as afterEach
.
I would recommend not traversing internal Mocha structures and instead doing something like:
describe('main describe', function() {
var prop;
afterEach(function() {
console.log(prop);
});
describe('sub', function() {
it('should do something', function() {
prop = 'test';
});
});
});
source to share