Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

typescript - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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);
  });
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...