如何扩展 Mocha 的 Context 接口? [英] How to extend Mocha's Context interface?

查看:31
本文介绍了如何扩展 Mocha 的 Context 接口?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

采用以下代码片段:

import { Foo } from "./foo";

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

这是在安装了 @types/mocha 包的项目中,以便编译器可以推断出 Mocha 命名空间.

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

TypeScript 编译器抛出以下错误:

The TypeScript compiler throws the following error:

没有与此调用匹配的过载.

No overload matches this call.

我查找了 ,并且似乎 mocha 期望传递给 beforebeforeEachit 等的任何函数,钩子是链接到 @types/mocha 中定义的 Context 类型 - 它不接受任何后代类型.

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.

如何解决这个问题并在我的测试环境中扩展 Mocha Context 接口?

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

推荐答案

使用派生接口从字面上扩展 mocha 的 Context 类型并不是您想要在这里做的事情.相反,您希望增加库定义的类型,添加您的成员.

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

示例用法:

describe("my test suite", function() {
  it("should do something", function() {
    console.log(this.foo);
  });
});

这篇关于如何扩展 Mocha 的 Context 接口?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆