How to add types to "this" keyword in mocha tests?

Viewed 946

I'm initialing some async data in my mocha tests using the delayed root suite functionality.

In my top-most beforeEach, I'm creating some objects with specific types and store them in the this object. In the child test files in the it suites, I'm using this to avoid duplicating the code countless times, but I'm losing the typings by doing so:

it("should do something", async function() {
  await this.token.approve(account, amount);
});

To get back them back (particularly the auto-complete functionality), I have to add an additional line of code:

const token: Erc20 = this.token;
await token.approve(account, amount);

I know that I could do this inline by casting with parentheses, yet I'd prefer to not do that.

Is there any way to define the typings for the "this" owner object of all test suite functions?

1 Answers

You can extend Mocha's Context interface and declare your additional test-context properties.

interface MyContext extends Mocha.Context {
  token: Erc20;
}

In your test functions, you can add type information for this parameter as follows:

it('should do something', async function(this: MyContext) {
  await this.token.approve();
});

UPDATE

The code above does not compile in strict mode (error TS2769: No overload matches this call.) See https://stackoverflow.com/a/62283449/69868 for an alternative solution.

Related