javascript - 如何在 Typescript Mocha 测试挂钩中保留“this”
问题描述
在下面的示例中,token.test.ts
将测试夹具加载到this.token
中beforeEach
,以便在 中的钩子中重用token.behavior.ts
。
// token.test.ts
import { shouldBehaveLikeToken } from './token.behavior';
describe("TokenTest", function () {
beforeEach('reload token fixture', async function () {
({ token: this.token }) = await loadFixture();
});
shouldBehaveLikeToken();
// More behavioral test suites
});
// token.behavior.ts
export function shouldBehaveLikeToken(): void {
describe('balanceOf', function () {
it('returns the correct balance', async function() {
expect(await this.token.balanceOf(ADDRESS).to.equal(2)); // WORKS!
});
});
function balanceOf() {
return this.token.balanceOf(ADDRESS); // DOES NOT COMPILE WITH THIS FUNCTION!
}
}
不管嵌套的断言有多深this.token
,我都可以this.token
在 Mocha 钩子 ( describe()
/ it()
) 中进行访问。
但是,如果我创建一个帮助函数this.token
来使测试在测试套件中更加可组合,我会得到错误'this' implicitly has type 'any' because it does not have a type annotation
和An outer value of 'this' is shadowed by this container
. 不管它是否是箭头函数,也不管函数是在哪里定义的,都会发生这种情况。
有人可以解释发生了什么吗?如何制作一个使用块中保留的辅助this
函数beforeEach
?
解决方案
看起来您的外部函数balanceOf
要求this
上下文Mocha.Context
是仅在 Mocha 测试内部可用的上下文。您必须指定函数的this
类型balanceOf
,然后将函数Mocha.Context
显式绑定到上下文,如下所示:
export function shouldBehaveLikeToken(): void {
describe('balanceOf', function () {
it('returns the correct balance', async function() {
// It is only within this callback that your `this` context is `Mocha.Context`.
// The context will not carry over outside of the callback.
expect(await balanceOf.bind(this)().to.equal(2)); // Bind the function here.
});
});
function balanceOf(this: Mocha.Context) { // explicit `this` type here.
return this.token.balanceOf(ADDRESS);
}
}
您的第一个balanceOf
函数无法正确键入this
的原因是因为所有函数声明(使用function
关键字创建的函数)都将绑定window
或global
默认绑定,或者undefined
如果您处于严格模式下。您可以在此处阅读有关函数如何绑定其this
上下文的更多信息。
推荐阅读
- reactjs - react-select focus() 更改后不显示光标
- ios - 我有 UIView 扩展,在这个扩展中我有一个方法 setDarkModeColor 如何在每次初始化视图时调用
- swift - C 中的 FTDI D2XX API 在命令行控制台上工作,但在由 Xcode 和 Swift 编程在 macOS 上构建的应用程序中始终返回零
- opengl - 如何从帧缓冲区翻转数据
- javascript - MongoDB Mongoose 在默认 createdAt 时间戳中按日期分组
- php - 修复 prestashop 错误。在分面搜索处于活动状态时进行排序时,某些产品会消失
- python - Django REST API 查询相关字段
- apache-nifi - Apache NiFi 的用例?
- laravel - Laravel 返回给定 id 的错误数据
- java - 错误-> cucumber.runtime.CucumberException:无法实例化类
- 此类没有空的或启用页面的构造函数”