Retrieve the current test's name within a Mocha test using Typescript

1.9k Views Asked by At

This question is very similar to this one, but has one very significant difference: typescript is used.

I'm trying to get current test title from within the mocha test, but since typescript is used this code does not work:

import 'mocha';

describe("top", () => {
    console.log(this.title);
    console.log(this.fullTitle());

    it("test", () => {
        console.log(this.test.title);
        console.log(this.test.fullTitle());
    });
});

Typescripts obscures this and access to native JavaScript's this is not possible anymore.

Has anyone faced this situation before? Is there any workaround for it?

1

There are 1 best solutions below

3
Madara's Ghost On BEST ANSWER

Your problem isn't that you use TypeScript, it's that you use arrow functions.

Arrow functions automatically bind this to the this where the function is defined.

Since they all use arrow functions, your this is the this found at the global level, which is either global outside of strict mode, or undefined in strict mode. (Since you're using ES modules, per-spec you are automatically in strict mode)

import 'mocha';

describe("top", function() {
    console.log(this.title);
    console.log(this.fullTitle());

    it("test", function() {
        console.log(this.test.title);
        console.log(this.test.fullTitle());
    });
});