Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend Mocha's Context interface?

Take the following code snippet:

import { Foo } from "./foo";

export interface MyContext extends Mocha.Context {
  foo: Foo;
}

This is in a project with the @types/mocha package installed, so that the Mocha namespace can be inferred by the compiler.

Now, if I try to use this interface in a test suite:

import { MyContxt } from "../types/mocha";

describe("my test suite", function() {
  it("should do something", function(this: MyContext) {
    ...
  });
});

The TypeScript compiler throws the following error:

No overload matches this call.

I looked up the source code, and it seems that mocha expects any function passed to the before, beforeEach, it, etc., hooks to be linked to a Context type as defined in @types/mocha - it doesn't accept any descendant types.

How can I go around this and extend the Mocha Context interface in my testing environment?

like image 311
Paul Razvan Berg Avatar asked Sep 05 '25 02:09

Paul Razvan Berg


1 Answers

Literally extending mocha's Context type using that derived interface is not what you want to do here. Instead, you want to augment the type defined by the library, adding your member.

This can be accomplished as follows:

// augmentations.d.ts
import {Foo} from './foo';

declare module "mocha" {
  export interface Context {
    foo: Foo;
  }
}

Example usage:

describe("my test suite", function () {
  it("should do something", function () {
    console.log(this.foo);
  });
});
like image 174
Aluan Haddad Avatar answered Sep 07 '25 16:09

Aluan Haddad