簡體   English   中英

如何在 Typescript Mocha 測試鈎子中保留“this”

[英]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 annotationAn 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 )默認將綁定windowglobal ,或者如果您處於嚴格模式,則綁定到undefined 您可以在此處閱讀有關函數如何綁定其this上下文的更多信息。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM