首页 > 解决方案 > 如何在 Typescript Mocha 测试挂钩中保留“this”

问题描述

在下面的示例中,token.test.ts将测试夹具加载到this.tokenbeforeEach,以便在 中的钩子中重用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 annotationAn outer value of 'this' is shadowed by this container. 不管它是否是箭头函数,也不管函数是在哪里定义的,都会发生这种情况。

有人可以解释发生了什么吗?如何制作一个使用块中保留的辅助this函数beforeEach

标签: javascripttypescriptmocha.js

解决方案


看起来您的外部函数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关键字创建的函数)都将绑定windowglobal默认绑定,或者undefined如果您处于严格模式下。您可以在此处阅读有关函数如何绑定其this上下文的更多信息。


推荐阅读