2

In mocha,

describe('this message text', function(){
    it('and this message text', function(done){
        console.log(this); // {} is empty
    });
});

How to access 'this message text' 'and this message text' from inside the tests?

I tried this object but it's empty.

laggingreflex
  • 32,948
  • 35
  • 141
  • 196

2 Answers2

5

As you discovered, accessing this inside the callback for it does not work. Here's one way to do it:

describe('this message text', function () {
    var suite_name = this.title;
    var test_name;

    beforeEach(function () {
        test_name = this.currentTest.title;
    });

    it('and this message text', function () {
        console.log(suite_name, test_name);
    });

    it('and this other message text', function () {
        console.log(suite_name, test_name);
    });
});

The workaround in the code above is that the beforeEach hook grabs the test name before the test is run and saves it in test_name.

If you wonder what the value of this is inside a test callback, it is the value of the ctx field on the suite to which the test belongs. For instance, the console.log statement in this:

describe('suite', function () {
    this.ctx.foo = 1;

    it('test', function () {
        console.log(this);
    });
});

would output:

{
  "foo": 1
}
Louis
  • 146,715
  • 28
  • 274
  • 320
4

this.test.parent.title;

Ctx for a suite has a test object which represents the currently executing test which has a parent to the suite (describe) above it.

You can also access the title of the current test by this.test.title etc.

This method allows getting the data (and other data) you are looking for without having to grab it in the before() etc functions.

1ac0
  • 2,875
  • 3
  • 33
  • 47