How to extend Mocha's Context interface?

强颜欢笑 提交于 2020-06-22 04:33:09

问题


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?


回答1:


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


来源:https://stackoverflow.com/questions/62282408/how-to-extend-mochas-context-interface

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!