如何在摩卡测试中为"this"关键字添加类型?



我正在使用延迟根套件功能在摩卡测试中初始化一些异步数据。

在我的最顶层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"所有者对象的类型?

您可以扩展 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 以获取替代解决方案。

相关内容

最新更新