[英]How to preserve "this" within Typescript Mocha test hooks
在下面的例子中, 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
上嵌套的斷言有多深,我都可以在 Mocha 鈎子( describe()
/ it()
)中訪問this.token
就好了。
但是,如果我創建一個使用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
。 不管它是否是箭頭函數,也不管函數在哪里定義,都會發生這種情況。
有人可以解釋發生了什么嗎? 如何創建一個使用beforeEach
塊中保留的this
的輔助函數?
看起來您的外部函數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
關鍵字創建的function
)默認將綁定window
或global
,或者如果您處於嚴格模式,則綁定到undefined
。 您可以在此處閱讀有關函數如何綁定其this
上下文的更多信息。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.