如何在 mocha 测试中向 "this" 关键字添加类型?
How to add types to "this" keyword in mocha tests?
我正在使用 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" 所有者对象定义类型?
您可以扩展 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.
) 请参阅 了解替代解决方案。
我正在使用 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" 所有者对象定义类型?
您可以扩展 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.
) 请参阅