【问题标题】:How to add types to "this" keyword in mocha tests?如何在 mocha 测试中为“this”关键字添加类型?
【发布时间】:2020-06-09 23:04:12
【问题描述】:

我正在使用 delayed root suite 功能在我的 mocha 测试中初始化一些异步数据。

在我最顶层的beforeEach 中,我正在创建一些具有特定类型的对象并将它们存储在this 对象中。在it 套件的子测试文件中,我使用this 来避免重复代码无数次,但这样做会丢失打字:

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

为了取回它们(尤其是自动完成功能),我必须添加一行额外的代码:

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

我知道我可以通过使用括号进行强制转换来内联,但我不想这样做。

有没有办法为所有测试套件函数的“this”所有者对象定义类型?

【问题讨论】:

  • 我认为 TypeScript 的标准做法是使用词法范围,例如github.com/mochajs/mocha/issues/2245#issuecomment-218321301.
  • 你可以使用declaration merging来扩展Mocha的this类型。但这将为 all Mocha 测试声明属性,而不仅仅是该文件中的那些。
  • 使用词法范围,我必须通过函数参数传递一个 bajillion 变量。此外,正如 GitHub 用户 iknowcss 在他的 comment 中所说的那样,这个解决方案还有其他缺点。
  • 啊,“词法范围”是指在封闭范围内声明一个变量并分配给/从中读取。这也是 iknowcss 支持的。

标签: typescript types mocha.js this


【解决方案1】:

您可以扩展 Mocha 的 Context 接口并声明您的其他测试上下文属性。

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

在您的测试函数中,您可以为this 参数添加类型信息,如下所示:

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

更新

以上代码无法在strict 模式下编译 (error TS2769: No overload matches this call.) 请参阅https://stackoverflow.com/a/62283449/69868 以获取替代解决方案。

【讨论】:

  • 不幸的是,这不起作用:No overload matches this call... Type "Context" is not assignable to type "MyContext"。我是否必须在某些 mocha 配置中指定新的上下文类型?
  • 原因似乎是 Mocha 期望传递给beforebeforeEachit 等的函数具有Context 类型。它不接受后代类型。 Link to the source code.
  • 我最终接受了这个答案,因为它恰当地解决了“this”关键字问题,以及I posted another question for this type inheritance puzzle
  • 很奇怪。我创建了一个小的 TypeScript 文件,它在非严格模式下编译得很好。启用strict 模式后,我能够重现编译问题。
猜你喜欢
  • 1970-01-01
  • 2013-10-14
  • 2019-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-21
  • 2018-11-24
相关资源
最近更新 更多