我正在使用延迟的根套件功能在我的Mocha测试中初始化一些异步数据。
在最顶层beforeEach
,我正在创建一些具有特定类型的对象,并将它们存储在此对象中。在it
套件的子测试文件中,我一直在使用this
以避免避免无数次重复代码的方法,但是这样做却会丢失类型:
it("should do something", async function() {
await this.token.approve(account, amount);
});
为了找回它们(特别是自动完成功能),我必须添加另一行代码:
const token: Erc20 = this.token;
await token.approve(account, amount);
我知道我可以通过用括号进行强制转换来内联地执行此操作,但我宁愿不这样做。
是否可以定义所有测试套件功能的“此”所有者对象的类型?
您可以扩展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。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句